Apache 2.4.9 on Debian 7.8 - .htaccess options not allowed

Question: I'm part the team that administrates a Apache 2.4.9 web server running on Debian 7.8. We're having an issue with one of our users website:
www.example.com/~user
When we try to access this URL, a page loads with the following content:

Internal Server Error
The server encountered an internal error or misconfiguration and was
  unable to complete your request.
Please contact the server administrator, webmaster@localhost and
  inform them of the time the error occurred, and anything you might
  have done that may have caused the error.
More information about this error may be available in the server error
  log. Apache/2.2.22 (Debian) Server at www.cpdee.ufmg.br Port 80

And in /var/log/apache2/error.log I find this:
[Fri Apr 03 11:36:36 2015] [alert] [client 188.8.131.52] /home/web/user/.htaccess: Options not allowed here

If I then look the content of the /home/web/user/.htacces file, there's just this configuration line:
Options -Indexes

After a quick research, it seemed to me that this issue has to do with Apache's virtual host configuration. Specifically, this tutorial says that this problem can be fixed by adding "Options" in the "AllowOverride" list of the /etc/apache2/sites-enabled/000-default, like this:
<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride FileInfo Options
    Order allow,deny
    allow from all
</Directory>

This file is just a link to the /etc/apache2/sites-available/default file and, in my case, this file looks a little bit messy:
<VirtualHost *:80>
        ServerAdmin webmaster@localhost

        DocumentRoot /var/www
        <Directory />
                Options FollowSymLinks
                AllowOverride Options
        </Directory>
        <Directory /var/www/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride Options
                Order allow,deny
                allow from all
        </Directory>

        ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
        <Directory "/usr/lib/cgi-bin">
                AllowOverride None
                Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
                Order allow,deny
                Allow from all
        </Directory>

        ErrorLog ${APACHE_LOG_DIR}/error.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn

        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

As suggested, I added Options to the AllowOverried list (for each <Directory> ... </Directory> "tag" I found there). Then I enabled the changes and reloaded Apache with this set of commands:
a2ensite default
/etc/init.d/apache2 reload

Even with these changes, I still kept having the same issue and I don't really know what's wrong. Could someone please help me with that?
Comment: This looks OK for /var/www but are your user home directories in /var/www or something like /home/user/public_html ?
Comment: It's in /home/users/
Answer: Check if more specific configuration in userdir.conf overrides settings you specify in <Directory />. In /etc/apache2/mods-enabled/userdir.conf is specified Directory directive for userdir, default is:
<IfModule mod_userdir.c>
        UserDir public_html
        UserDir disabled root

        <Directory /home/*/public_html>
                AllowOverride FileInfo AuthConfig Limit Indexes
                Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
                <Limit GET POST OPTIONS>
                        Order allow,deny
                        Allow from all
                </Limit>
                <LimitExcept GET POST OPTIONS>
                        Order deny,allow
                        Deny from all
                </LimitExcept>
        </Directory>
</IfModule>

So you should add Options to the AllowOverride directive here.
(Probably your directory is <Directory /home/web/*/> instead.)
Comment: Esa, that solved my problem, thank you! And yes, my directory is ``


Proc syntax in Haskell Arrows leads to severe performance penalty

Question: Using proc notation for Arrow seems to kill performance in my project. Here is a toy example of the problem:
We define Coroutine newtype (mostly copying from Generalizing Streams into Coroutines) to represent Mealy machines (i.e. functions that carry some state) with instances of Category and Arrow, write scan wrapper function and evalList runner function for lists.
Then we have sumArr and sumArr' functions where the latter is the former called within proc block.
Compiling with stack ghc -- --make test.hs -O2 using ghc-8.0.2 on OS X I get runtime of 0.087 secs for sumArr and 3.263 secs for sumArr' (with a heavy memory footprint).
I would like to know if this in fact caused by using proc and if I can do something to have normal runtime behaviour when using proc notation (writing arrow code without it is painful). Thank you.
{-# LANGUAGE Arrows #-}
{-# LANGUAGE BangPatterns #-}

import Prelude hiding (id, (.))
import Control.Arrow
import Control.Category
import qualified Data.List as L

newtype Coroutine i o = Coroutine { runC :: i -> (o, Coroutine i o) }

instance Category Coroutine where
    id = Coroutine $ \i -> (i, id)

    cof . cog = Coroutine $ \i ->
        let (x, cog') = runC cog i
            (y, cof') = runC cof x
        in (y, cof' . cog')

instance Arrow Coroutine where
    arr f = Coroutine $ \i -> (f i, arr f)

    first co = Coroutine $ \(a,b) ->
        let (c, co') = runC co a in ((c,b), first co')

scan :: (o -> t -> o) -> o -> Coroutine t o
scan f = go where
    go i = Coroutine $ step i where
            step a b = let !a' = f a b in (a', go a')

evalList :: Coroutine a b -> [a] -> [b]
evalList a = L.map fst . L.drop 1 . L.scanl' (\(_, acc) v -> let !x = runC acc v in x) (undefined, a)

sumArr, sumArr' :: Coroutine Int Int
sumArr = scan (\acc x -> let !newAcc = acc + x in newAcc) 0
sumArr' = proc v -> do sumArr -< v

testData :: [Int]
testData = [1..1000000]

main = print $ L.last $ evalList sumArr' testData

Comment: Have you looked at the core to see how the two functions differ?
Answer: Yeah, this is probably caused by proc notation. The desugaring is very low-level, introducing a lot of (needless) arrs and not taking advantage of &&& or *** at all.
For example, last I checked, this:
mulA f g = proc x -> do
  a <- f -< x
  b <- g -< x
  returnA -< a * b

Is desugared to something like this:
mulA f g = arr dup
  >>> first f
  >>> arr swap
  >>> first g
  >>> arr mul
  where
    dup x = (x, x)
    swap (x, y) = (y, x)
    mul = uncurry (*)

When it could be just this:
mulA f g = f &&& g >>> arr mul

And this:
proc x -> do
  a <- f -< x
  b <- g -< a
  returnA -< b

Becomes something like this:
arr id
  >>> f
  >>> arr id
  >>> g
  >>> arr id
  >>> returnA

Instead of this:
f >>> g

Moreover I don't think there are any GHC rewrite rules that take advantage of the arrow laws to help account for this.
Comment: @AJFarmar: That seems like the logical next step. I suspect that rewrite rules won't be able to address all of the issues, though, so I'd also suggest filing a GHC ticket, or posting a message to the Glasgow Haskell Users or Haskell Cafe lists, to gauge interest in a proposal for an improved desugaring. I guess the main reason it's unoptimised is that there are relatively few people using arrow notation.
Comment: Thank you for your answer and suggestions, I will ask this on the mailing list as well and post back here.
Comment: So, what to do? Could we write our own rewrite rules?
Answer: I have found arrowp-qq which wraps proc blocks inside quasiquotes and seems to produce better output than native desugarer. Performance is restored in the following version of our example:
{-# LANGUAGE QuasiQuotes #-}
...
import Control.Arrow.QuasiQuoter
...
sumArrQQ = [proc| x -> do sumArr -< x |]

One issue that I bumped into is that these quasiquotes don't play nicely with raw numbers inside the quotation.
sumArrQQ' = [proc| x -> do sumArr -< x + 2 |] -- gives an error

sumArrQQ'' = [proc| x -> do sumArr -< plus2 x |] -- compiles fine
    where plus2 = (+) 2


JavaScript Import file by absolute path

Question: I have a module named foo in a dependencies directory:
import foo from '../dependencies/foo'; // works fine

The issue is that the import should be on a different path because it's deployed in an AWS dependency layer (different path). Something like this:
import foo from '/opt/dependencies/foo';

But I am getting this error:

Cannot find module '/opt/dependencies/foo' or its corresponding type declarations.ts(2307)

I can use a require() but it gives me a warning telling me to use an import statement instead.
const foo = require('/opt/dependencies/foo');

What can I do to avoid this error while keeping the /opt path?
Answer: You can use an the ES6 dynamic import() function, although it is asynchronous. If you're using an environment that supports top-level await, then you can simply do this:
const foo = await import('/opt/dependencies/foo.js');

If you're using an older version of node (you'll know because you'll get an error), then you'll need to wrap your whole program in an async function (the technical term is an IIFE). Like this:
(async () => {
  const foo = await import('/opt/dependencies/foo.js');

  /* rest of your program */
})();

Comment: I get the same error with await import
Comment: Top-level 'await' expressions are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher.ts(1378)
Comment: @TiagoSilva Yes. If your environment isn't configured to those settings, then you'll need to use my second piece of code, or upgrade :)

JavaScript Import file by absolute path


Erro: Service Intent must be explicit

Question: Ola, estou tendo o seguinte erro no android, alguém me pode ajudar?
Erro: Service Intent must be explicit: Intent { act=SERVICEPUSHNET }

Codigo:
SMART.JAVA
package imm.pt.immsmart;

            import android.content.Intent;
            import android.support.v7.app.ActionBar;
            import android.support.v7.app.AppCompatActivity;
            import android.os.Bundle;
            import android.util.Log;
            import android.widget.ProgressBar;
            import android.widget.TextView;

            import org.json.JSONException;
            import org.json.JSONObject;

            public class SMART extends AppCompatActivity {
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_smart);
                    ActionBar actionBar = getSupportActionBar();
                    actionBar.hide();
                    callServer("get-consumo", "");
                    // Service
                    Intent it = new Intent("SERVICEPUSHNET");
                    startService(it);
                }
                private void degenerateJSON(final String data){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            TextView apre = findViewById(R.id.apre);
                            ProgressBar progress = findViewById(R.id.percentagem);
                            TextView mbfalta = findViewById(R.id.mbfalta);
                            TextView total = findViewById(R.id.total);
                            TextView pacote = findViewById(R.id.pacote);
                            try{
                                JSONObject jo = new JSONObject(data);
                                apre.setText(jo.getString("apre"));
                                progress.setProgress(jo.getInt("percentagem"));
                                mbfalta.setText(jo.getString("mbfalta"));
                                total.setText(jo.getString("total"));
                                pacote.setText(jo.getString("pacote"));

                            }catch(JSONException e) {e.printStackTrace();}
                        }
                    });

                }
                private void callServer(final String method, final String data){
                    new Thread(){
                        public void run() {
                            String answer = HttpConnection.getSetDataWeb("http://192.168.1.70/myIMM/api.php", method, data);
                                degenerateJSON(answer);
                        }
                    }.start();
                }
            }

ServicoPush.java
package imm.pt.immsmart;

                import android.app.Notification;
                import android.app.NotificationManager;
                import android.app.Service;
                import android.content.Intent;
                import android.graphics.BitmapFactory;
                import android.media.Ringtone;
                import android.media.RingtoneManager;
                import android.net.Uri;
                import android.os.IBinder;
                import android.support.v4.app.NotificationCompat;
                import java.util.ArrayList;
                import java.util.List;

                public class ServicoPush extends Service{

                    public List<Worker> threads = new ArrayList<Worker>();

                    @Override
                    public IBinder onBind(Intent intent) {
                        return null;
                    }
                    @Override
                    public void onCreate(){
                        super.onCreate();
                    }
                    @Override
                    public int onStartCommand(Intent intent, int flags, int startId){
                        Worker w = new Worker(startId);
                        w.start();
                        threads.add(w);
                        return(super.onStartCommand(intent, flags, startId));

                    }
                    class Worker extends Thread{
                        public int startId;
                        public boolean ativo = true;

                        public Worker(int startId){
                            this.startId = startId;
                        }

                        public void run(){
                            while (ativo){
                                try {
                                    Thread.sleep(3000);
                                    //Notificação
                                    notifica();
                                    ativo = false;
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                    @Override
                    public void onDestroy(){
                        super.onDestroy();
                        for(int i = 0, tam = threads.size(); i < tam; i++){
                            threads.get(i).ativo = false;
                        }
                    }
                    public void notifica(){
                        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
                        builder.setTicker("Limite de Dados Moveis");
                        builder.setContentTitle("IMM SMART");
                        builder.setContentText("Estas quase a atingir o teu limite de dados!");
                        builder.setSmallIcon(R.drawable.ic_launcher_background);
                        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_background));
                        Notification n = builder.build();
                        n.vibrate = new long[]{150, 300, 150, 600};
                        nm.notify(R.drawable.ic_launcher_background, n);
                        try{
                            Uri som = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                            Ringtone toque = RingtoneManager.getRingtone(this, som);
                            toque.play();
                        }catch (Exception e) {e.printStackTrace();}
                    }
                }

Android Manifests:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="imm.pt.immsmart">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".SMART">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service android:name=".ServicoPush" android:label="SERVICEPUSHNET" android:exported="false">
        <intent-filter>
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="SERVICEPUSHNET" />
        </intent-filter>
    </service>
    <receiver android:name=".BroadCastPush" android:label="BroadCastPush" android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>
</application>

Answer: Por questões de segurança os serviços devem ser iniciados explicitamente e não devem ter intent filters declarados.
A partir do Android 5.0 é lançada essa excepção.
Declare o seu serviço assim:
<service android:name=".ServicoPush"/>

Inicie-o assim:
Intent serviceIntent = new Intent(this, ServicoPush.class);
startService(serviceIntent);

Tenha também em conta as limitações impostas pelo Android 8 à execução de serviços em background.

Erro: Service Intent must be explicit


angular controller only picks up the input values changed

Question: I've got a fairly simple angular controller method :
$scope.addComment = function () {
        if ($scope.newComment.message) {
          $scope.can_add_comments = false;
          new Comments({ comment: $scope.newComment }).$save(function (comment) {
            $scope.comments.unshift(comment);
            return $scope.can_add_comments = true;
          });
          return $scope.newComment = {};
        }
      };

And in my form I have a textarea that holds the value of comment :
<textarea class="required" cols="40" id="new_comment_message" maxlength="2500" ng-disabled="!can_add_comments" ng-model="newComment.message" required="required" rows="20"></textarea>

Works great so far, however I do want to send some data, hidden data with the comment as well. So I added something to hold that value :
<input id="hash_id" name="hash_id" ng-init="__1515604539_122642" ng-model="newComment.hash_id" type="hidden" value="__1515604539_122642">

However when I inspect the $scope.newComment it always comes back as an object with only message as it's property, which is the value from the text area, and I don't get the property on the object hash_id.
When I make this input non hidden and I manually type in the value into the input field and submit a form, I do get a object with hash_id property. What am I doing wrong here, not setting it right?
Comment: what are the properties in newComment? It sounds like you dont have hash_id on newComment. When you manually edit it, angular adds  ( newComment['hash_id'] = newValue) . can you do a jsfiddle?
Comment: @DhanaKrishnasamy By manually I mean when I type in the input field and press the submit
Comment: ``
 May work
Comment: @ODelibalta doesn't work also without ng-init and with just ng-value
Comment: I am not sure what to do the way you want to do. Since you are initializing a value to a variable in your scope, I think you should make that in your controller.
Answer: As far as I know, ng-model doesn't use the value property as a "default" (i.e. it won't copy it back into your model). If you want a default, it should be placed wherever the model is defined:
$scope.newComment = { hash_id: "__1515604539_122642", /* Other params */ };
Alternatively, changing the ng-init to an assignment should work (though I would recommend  the above solution instead):
<input id="hash_id" name="hash_id" ng-init="newComment.hash_id = '__1515604539_122642'" ng-model="newComment.hash_id" type="hidden">
Comment: I'd say this is pretty spot on, although I am curious as to why init is being used in the first place.
Comment: Given that init has the same value as the `value` property, my guess is that the OP was hoping it would assign its value as the initial value for the model.


Google Apps Script generates float instead of Integer (but not always!?!)

Question: I have a custom script in a Purchase Requests spreadsheet. It generates new tabs and adds links from the new tab to 'register' (the first tab) in order to summarize the data.
Unfortunately, the tab name often gets generated in float format (206.0) instead of integer format, so the tab name references, which are always in integer format, don't work. I can't figure out why the float is appearing.  It doesn't happen on every computer we try it on, only most, which makes it even more mysterious.
I've tried different methods for coercing it to an integer but haven't found a solution.  All suggestions gratefully welcomed.
function newPR(e) {
  // First, set up the variables we'll need
  var ui = SpreadsheetApp.getUi()
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
  var sheet = sheets[0];
  var templateSheet = sheets[1];
  var highestPurchaseRequest = sheets[3];
  var today = new Date();
  var requestCount = sheet.getRange(6,1).getValue();  //getRange: row, column
  var lastRequestTab = parseInt(highestPurchaseRequest.getName(),10);
  var checkNeeded = ( requestCount != lastRequestTab );
  var loopCount = 0;
  /* Before starting, check whether the highest request number matches the
     name of the highest estimate tab created so far. If not, try to fix it a few
     times.  If you can't fix it automatically, flag an error and ask the user to
     sort it out.
  */
  if( checkNeeded ) {
    while( loopCount < 100 && checkNeeded ) {
      if( requestCount <= lastRequestTab ) {
        requestCount++;
      } else {
        checkNeeded = false;
      }
      loopCount++
    }
    if( checkNeeded ){
      ui.alert("Something went wrong!",'The highest Purchase Request listed on the Summary tab is lower than leftmost Purchase Request tab in the spreadsheet.\n\nI\'ve tried to fix this automatically but haven\'t been able to. Maybe someone dragged tabs into a different order accidentally? The order should be: Register, TemplatePO, TemplateCS, Highest-numbered-request.\n\nPlease correct it and retry. ',ui.ButtonSet.OK);
      return;
    }
  }
    /* Everything looks good, so create a new sheet using "templatePO" as the template,
       increment the request number and use it to name the new sheet; fill in the
       current date & estimate number at the top
    */
    requestCount = ++requestCount >> 0;
    ss.insertSheet(requestCount.toString(), 3, {template: templateSheet});
    // Now that it's made, we need another variable to store a reference to the new sheet
    var newSheet = SpreadsheetApp.getActiveSheet();
    newSheet.getRange(5,9).setValue( today );

    // Switch to the summary sheet and add links to the new data
    ss.setActiveSheet( sheets[0] );
    ss.insertRowBefore(6);
    var newCells = sheet.getRange(6,1,1,9);
    // Data from: PR# in I2, Date in I5, From in D4, For/Description in D5, Total in D7, sent in K2, received in K11, Notes in K5
    var requestData = [ [ requestCount, "='" + requestCount + "'!I5", "='" + requestCount + "'!D4", "='" + requestCount + "'!D5", "='" + requestCount + "'!K2", "='" + requestCount + "'!K11", "='" + requestCount + "'!D7","",""] ]
    newCells.setFormulas( requestData );

    // Switch back to the new sheet & get ready for user input
    ss.setActiveSheet( newSheet );
    newSheet.setActiveSelection("D5");
}

Comment: Can you provide a sample test Spreadsheet with the corerct structure for this to run?
Comment: Sure, try this: https://docs.google.com/spreadsheets/d/1VjApHmSOZ9Et47McctfDzmebINY3B_zpbLms41pc93k/edit?usp=sharing
Comment: [Seems to be working without any issue for me](https://imgur.com/NEq84XZ.png)?
Comment: Please show what you have tried and add a brief description of your search efforts as is suggested in [ask] (have you tried to use `parseInt()`? if so, how?)
Answer: To convert a number to a string with no decimal part, you can use toFixed(0).
Try changing
ss.insertSheet(requestCount.toString(), 3, {template: templateSheet});

to
ss.insertSheet(requestCount.toFixed(0), 3, {template: templateSheet});


Add new repository in Subversive

Question: As I know we can use Visual-SVN for server and Tortoise-SVN for client as practice.
However, What if we are going to use subversive? Can subversive be both server and client? And if we going to use subversive as server,
how do we allow users to connect with it in 24 hour basis?
open public IP and keep running the Eclipse?
Answer: Subversive is just a plugin for Eclipse. Server and Client are different things.
For the server you can use whatever server you like. It can be Tortoise, VisualSVN or even download and compile the source by yourself. Apache does not provide binaries. If you don't want to build the packages by yourself, you can look for binary packages here.
Once you decided which package to use, if you use Windows, which I'm assuming you are, you can set the svnserve to run as a Windows service. Which means it can run in the background for 24/7.
The client does not have to be a part of the same package as the server. There is no problem in having VisualSVN as your server and to use Subversive as your client. The only thing you need to keep in mind is the SVN Version. Preferably the server and the client should be the same version.

Add new repository in Subversive


SoapUI not finding my web-service

Question: So I've been struggling with web-services for a couple of days now, and It seemed that I finally had a breakthrough.
I followed this tutorial to the letter, and I have my web-service up and running. The only problem is, that I can't seem to test it via soapUI.
If I go to http://localhost:8084/soapwebservices It displays the data about my web-service, eg, the location of wsdl, and so on. Judging by that, the link is correct.
But when I try to send this request to it:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soap="soapwebservices.jdevelop.eu">
   <soapenv:Header/>
   <soapenv:Body>
      <soap:calculateValues>
         <value1>10</value1>
         <value2>3.21</value2>
      </soap:calculateValues>
   </soapenv:Body>
</soapenv:Envelope>

I get a 404 error:
<title>Not Found (404)</title>

Not Found (404)

Original request: http://localhost:8084/soapwebservices

Not found request: http://localhost:8084/soapwebservices

Here is my WSDL:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<definitions xmlns:ns1="soapwebservices.jdevelop.eu" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:ns="http://schemas.xmlsoap.org/soap/encoding/" name="SOAPWebServices" targetNamespace="soapwebservices.jdevelop.eu">
    <types>
        <xsd:schema>
            <xsd:import namespace="soapwebservices.jdevelop.eu" schemaLocation="webservices.xsd"/>
        </xsd:schema>
    </types>
    <message name="calculateValues">
        <part name="calculateValues" element="ns1:calculateValues"/>
    </message>
    <message name="calculateValuesResponse">
        <part name="calculateValuesResponse" element="ns1:calculateValuesResponse"/>
    </message>
    <portType name="SOAPWebServices">
        <operation name="getCalculateValues">
            <input message="ns1:calculateValues"/>
            <output message="ns1:calculateValuesResponse"/>
        </operation>
    </portType>
    <binding name="SOAPWebServicesPortBinding" type="ns1:SOAPWebServices">
        <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
        <operation name="getCalculateValues">
            <soap:operation soapAction="urn:http://blog.jdevelop.eu/services/getCalculateValues"/>
            <input>
                <soap:body use="literal"/>
            </input>
            <output>
                <soap:body use="literal"/>
            </output>
        </operation>
    </binding>
    <service name="SOAPService">
        <port name="WebServices" binding="ns1:SOAPWebServicesPortBinding">
            <soap:address location="http://blog.jdevelop.eu:80/services"/>
        </port>
    </service>
</definitions>

What could be the problem here?
I am using Netbeans 6.0.1, Apache Tomcat 6.0 and Java SDK 1.7
Thanks!
Comment: I think you have to provide the full link , including the wsdl---_http://localhost:8084/soapwebservices/?wsdl
Comment: In some specific place, or in general?
Comment: when you create a new project in SoapUI, you provide a name (first textbox) and the address of the service (this is the one which should be ending in /?wsdl)
Answer: Couple of observations:

In your SOAP message, the operation name you are sending is  calculateValues (<soap:calculateValues>) whereas the operation name mentioned in the WSDL is getCalculateValues (<operation name="getCalculateValues">). This may be the reason behind 404 error as calculateValues operation is not defined.
I assume that  you are not posting the SOAP message at the service URL mentioned in the WSDL (<soap:address location="http://blog.jdevelop.eu:80/services"/>).
Comment: I indeed was. Meh, such a rookie mistake.
Answer: Check the namespce in your endpoint class and the schema , both should be same

SoapUI not finding my web-service


Regex: como selecionar frase inteira (sem digitos) e inserir aspas

Question: Eu tenho esse resultado de um .csv
9   Abraço de tamanduá
9   Abraço fraterno
9   Correr/partir pro abraço (futebol)

Estou aplicando diversos regex para que o resultado final seja uma instrução SQL assim:
INSERT INTO `expressoes`(`id_palavra`, `expressao`) VALUES (9, 'Abraço de tamanduá'), (9, 'Abraço fraterno'), (9, 'Correr/partir pro abraço (futebol)')

Como sou newbie em regex, fiz um keybinding no vscode para executá-lo com um atalho (usando o find e replace all do vscode). Assim eu consigo executar diversos comandos regex em sequência.
Assim, no primeiro comando eu fiz:
find: \n{1,}
replace all: ), (

Resultando:
9   Abraço de tamanduá), (9 Abraço fraterno), (9    Correr/partir pro abraço (futebol)

O segundo comando:
find: (?<=[0-9])
replace all: ,

Resultando
9,  Abraço de tamanduá), (9,    Abraço fraterno), (9,   Correr/partir pro abraço (futebol)

Depois, os comandos 3, 4 e 5:
find: ^
replace all: (

find: $
replace all: )

find: \s // isso não funciona pelo plugin `ssmacro` que executa o comando regex
replace all: ␣ // corrigir `tab` com um espaço simples

só para corrigir o inicio e o final com parenteses. Resultando:
(9, Abraço de tamanduá), (9, Abraço fraterno), (9, Correr/partir pro abraço (futebol))

Agora, inserir as aspas simples na frase inteira eu não estou entendendo. Tentei ([a-z,A-z,çéáíãõ]+) (\w+) tb não deu. Consegui um próximo com esse:
find: ([^\d\W]+á*é*í*ó*ú*õ*ã*ç*(\s)*/*)
replace: '$1'

mas ainda não deu certo. resultando:
(9, 'Abraç''o ''de ''tamanduá'), (9, 'Abraç''o ''fraterno'), (9, 'Correr/''partir ''pro ''abraç''o '('futebol'))

Q: Alguma ideia para formatar corretamente as aspas simples?
Q: E ainda tem essa (...) como em (futebol) no final de algumas sentenças que eu não faço ideia em como isolá-lo.
Comment: Você quer remover da sentença tudo que vem antes do início da frase(o espaço e o dígito)?
Answer: Seria mais fácil usar alguma linguagem para ler o CSV, separar os campos e criar os inserts, mas se quer fazer com regex, vamos lá.
Uma opção é usar (\d+)\s+(.+):

\d+: um ou mais dígitos
\s+: um ou mais espaços
.+: um ou mais caracteres ("qualquer um", exceto quebras de linha - ou seja, vai até o final da linha)

Os dígitos e os caracteres depois do espaço estão entre parênteses para formar grupos de captura, assim eu consigo pegá-los posteriormente.
Na substituição você usa:
INSERT INTO `expressoes`(`id_palavra`, `expressao`) VALUES ($1, '$2');

Os trechos $1 e $2 equivalem aos grupos de captura (o primeiro são os dígitos e segundo é o restante do texto).
Só que isso vai gerar várias linhas com um INSERT em cada, e não apenas um único INSERT como você queria. Mas se quiser, você pode substituir por VALUES ($1, '$2'), e adicionar o INSERT INTO etc... no início manualmente.


Thrift - One way messaging

Question: Is there a way to implement a "fire-and-forget" asynchronous thrift method call, where the client just sends over information and forgets about it. No waiting for a response, or response callback. Kind of like a message queue, just without the queue. Is there any way to do this with thrift?
Answer: Yes, just add oneway to method definition. Of cause, oneway method must return void:
service MyService {
    //returns immediately
    oneway void onewayMethod(<params>);

    //blocks until completion
    void normalMethod(<params>);
}

Comment: exactly. But I'm not sure whether you really want it. It may happen that the server will not receive client call and the client will not know it! I think it's better to return void just to make sure that the request has been processed.

Thrift - One way messaging


Operator overload stops working in R package

Question: I have a container class that is basically a list. Because I wanted to support subsetting, I have overloaded the subset [ operator (likely poorly implemented).
#' Constructor for spectra object
.spectra = function(n_spectrum = 0) {
    object        = vector(mode = "list", n_spectrum)
    class(object) = "spectra"
    return(object)
}

#' Operator overload
#' @export
`[.spectra` = function(x, i) {
    x = unclass(x)
    x = x[i]                  # Using the list's subset function
    class(x) = "spectra"
    return(x)                 # Should return a "spectra" object, not a list
}

Now, this works as expected when in my development environment (when I'm debugging the package). That is, if y_old is a spectra object and I do y_new = y_old[-1], y_new is still a spectra object.
However, when I compile the project as a package and install it, the subsetting operator returns a list instead of a spectra object.
Any clue of what is going on?
EDIT
I forgot to mention that I'm using RStudio and the devtools library.
Comment: Do you have a line with `S3method("[",spectra)` in the `NAMESPACE` file of your package?
Comment: It doesn't match your pattern in `exportPattern("^[[:alpha:]]+")`. That looks for functions that start with letters. This particular function starts with a "["
Comment: @nicola No. The **only** line I have in `NAMESPACE`  is `exportPattern("^[[:alpha:]]+")`, which I guess is what RStudio puts in there.
Comment: Put that line, rebuild the package and see if it works.
Comment: @nicola This does work, though I'm curious why that is the only function that doesn't get exported automatically.
Comment: Thanks, that answer helped me. You should make it official so this question can be closed and we can upvote the solution.
Answer: This problem boils down to RStudio's default initialization of NAMESPACE when you choose to create a package. Inspecting the NAMESPACE file reveals:
exportPattern("^[[:alpha:]]+")

Which doesn't match the subset operator [, as MrFlick pointed out.
You can either add names to NAMESPACE manually or you can get RStudio and Roxygen to do the work for you. In RStudio 0.99.902 you would:

install.packages("roxygen2")
Check Generate documentation with Roxygen in the menu Build > Configure Build Tools > Build Tools.
Click on the Configure button and check the NAMESPACE file check box.

Now you obviously have to add Roxygen documentation to your functions and remember to use the @export tag, e.g.:
#' Print hi in R
#' @export
print_hi = function(x) print("hi")

After building you should have a automatically generated NAMESPACE file. For instance:
# Generated by roxygen2: do not edit by hand

export(print_hi)


azure blob storage async download with progress bar

Question: i am trying to get a COMPLETE example of downloading a file form Azure Blob Storage using the .DownloadToStreamAsync() method wired up to a progress bar.
i've found references to old implementations of the azure storage sdk, but they dont compile with the newer sdk (that has implemented these async methods) or don't work with current nuget packages.
https://blogs.msdn.microsoft.com/avkashchauhan/2010/11/03/uploading-a-blob-to-azure-storage-with-progress-bar-and-variable-upload-block-size/
https://blogs.msdn.microsoft.com/kwill/2013/03/05/asynchronous-parallel-blob-transfers-with-progress-change-notification-2-0/
i'm a newbie to async/await threading in .NET, and was wondering if someone could help me out with taking the below (in a windows form app) and showing how i can 'hook' into the progress of the file download... i see some examples dont use the .DownloadToStream method, and they instead download chunks of the blob file.. but i wondered since these new ...Async() methods exist in the newer Storage SDK's, if there was something smarter that could be done?
So assuming the below is working (non async), what additionally would i have to do to use the blockBlob.DownloadToStreamAsync(fileStream); method, is this even the right use of this, and how can i get the progress?
ideally i am after any way i can just hook the progress of the blob download so i can update a Windows Form UI on big downloads.. so if the below is not the right way, please enlighten me :)
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("mycontainer");

// Retrieve reference to a blob named "photo1.jpg".
CloudBlockBlob blockBlob = container.GetBlockBlobReference("photo1.jpg");

// Save blob contents to a file.
using (var fileStream = System.IO.File.OpenWrite(@"path\myfile"))
{
    blockBlob.DownloadToStream(fileStream);
}

Using the awesome suggested method (downloading 1mb chunks) kindly  suggsted by Gaurav, i have implemented using a background worker to do the download so i can update the UI as i go.
The main part inside the do loop that downloads the range to a stream and then writes the stream to the file system I havent touched from the original example, but i have added code to update the worker progress and to listen for the worker cancellation (to abort the download).. not sure if this could be the issue?
For completeness, below is everything inside the worker_DoWork method:
public void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        object[] parameters = e.Argument as object[];
        string localFile = (string)parameters[0];
        string blobName = (string)parameters[1];
        string blobContainerName = (string)parameters[2];
        CloudBlobClient client = (CloudBlobClient)parameters[3];

        try
        {
            int segmentSize = 1 * 1024 * 1024; //1 MB chunk
            var blobContainer = client.GetContainerReference(blobContainerName);
            var blob = blobContainer.GetBlockBlobReference(blobName);
            blob.FetchAttributes();
            blobLengthRemaining = blob.Properties.Length;
            blobLength = blob.Properties.Length;
            long startPosition = 0;
            do
            {
                long blockSize = Math.Min(segmentSize, blobLengthRemaining);
                byte[] blobContents = new byte[blockSize];
                using (MemoryStream ms = new MemoryStream())
                {
                    blob.DownloadRangeToStream(ms, startPosition, blockSize);
                    ms.Position = 0;
                    ms.Read(blobContents, 0, blobContents.Length);
                    using (FileStream fs = new FileStream(localFile, FileMode.OpenOrCreate))
                    {
                        fs.Position = startPosition;
                        fs.Write(blobContents, 0, blobContents.Length);
                    }
                }
                startPosition += blockSize;
                blobLengthRemaining -= blockSize;

                if (blobLength > 0)
                {
                    decimal totalSize = Convert.ToDecimal(blobLength);
                    decimal downloaded = totalSize - Convert.ToDecimal(blobLengthRemaining);
                    decimal blobPercent = (downloaded / totalSize) * 100;
                    worker.ReportProgress(Convert.ToInt32(blobPercent));
                }

                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    blobDownloadCancelled = true;
                    return;
                }
            }
            while (blobLengthRemaining > 0);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

This is working, but on bigger files (30mb for example), i sometimes am getting 'can't write to file as open in another process error...' and the process fails..
Answer: Using your code:
using (var fileStream = System.IO.File.OpenWrite(@"path\myfile"))
{
    blockBlob.DownloadToStream(fileStream);
}

It is not possible to show the progress because the code comes out of this function only when the download is complete. DownloadToStream function will internally split a large blob in chunks and download the chunks.
What you need to do is download these chunks using your code. What you have to do is use DownloadRangeToStream method. I answered a similar question some time back that you may find useful: Azure download blob part.
Comment: thank you for confirming.. will use the download in blocks example you have suggested and run on a seperate thread to UI so i can update the progress bar from bytes left etc.
Comment: i've implemented this on a background worker, and its all working nicely.. almost.. on some bigger files, the process errors sometimes on 'can't write to file as open in another process error...'  could this be a delay in writing out to the file system beofre it tries to write again?
Comment: Without looking at your code, it won't be possible to tell why you're getting the error. Would you mind sharing your latest code?
Comment: yes, no problem.. i am new here.. is it best to paste another answer so the code is readable/syntax highlighted  or do i post it in the comments.
Comment: Most preferred way would be to update your question and include the code you're using there. Alternately you could use something like pastebin or Github Gist and share the link in comment. It's not a good idea to put this information in comments :). HTH.


SBS domain name choice

Question: We are about to set up SBS 2011 at my small company < 10 users. My collaborator wants to name the SBS domain "example.local" . I'm of the opinion we should name the SBS domain "corp.example.com" and setup DNS so the "corp" record is a NS record to the SBS server's private IP.
FYI: "Example.com" isn't the real domain name and while the website is hosted outside our office, email will be stored on the SBS server in our office after passing though a spam filtering smart host hosted elsewhere too.
Comment: You want to name the domain corp.example.com and the server would be corp.corp.example.com?
Comment: @joeqwerty Presumable the server's hostname would be server.corp.example.com or server.example.local .
Comment: So, SBS 2011 Standard doesn't really give you a choice. During a new install you are only allowed to type a word with no periods, eg "example" and it will automatically append the ".local" to the domain name during the install.
Answer: We use the corp.example.com convention for our small domains. Don't use the .local tld for your domain as it is the tld for Zeroconf/Bonjour, thus any MacOS X clients would not be able connect easily. Also, using a real domain that is registered to you will make life easier for you and your users, especially when they are outside of your office.
Comment: I use .lcl to avoid the OS X Bonjour conflict.
Answer: I'd recommend using example.corp.  Typically administrators setup their internal domain name the same as their public domain name and simple things like getting to example.com can be problematic when it is also the internal domain.  In a small business perhaps that may also be preferred if it is also hosting the companies website/etc.
With using example.corp you have internal resolution and you can easily setup the records for example.com for resolution as needed and can give you added flexibility between internal and external resolution.
Answer: Personally, I'd go with example.local, which according to Wikipedia is Microsoft's recommended naming convention.
I can't find any info to back this up, however Microsoft do have an article regarding naming a domain, which should be useful to you.
I've done many installs using this naming convention, and it give you the flexibility to be be  able to assign internal and external DNS names to any system on the network as required. (e.g. test.example.local would point to the internal IP address, and test.example.com would point to its external IP address - assuming it is accessible to the outside world of course).
Note that you might find if you try to use test.example.com internally it won't work by default, but you can add another internal DNS zone (test.example.com) with a default record that points to the IP used by test.example.local, this way, test.example.com works internally and externally.
I also maintain systems for a customer that shares a .com internally and externally, and I'm constantly struggling with the duplicate DNS namespaces.
Edit: also note that .local is not a valid TLD according to RFC2606
Comment: Microsoft no longer recommend using .local.  Their recommendation is very vague as I have seen it these days, but some of their articles still reference it.
Comment: That probably explains why I struggled to find evidence to back this up, but regardless, from my experience, I would always recommend avoiding duplicating a DNS namespace at all costs.
Comment: I too have tripped up on differing but duplicated DNS for internet/public DNS lookups which is why "example.com" is not considered for the new SBS install.
Comment: Accepted because SBS 2011 standard forces the "example.local" choice as best as I can tell.
Comment: really? That's interesting. I wonder what would happen if an older version of SBS with a domain name of example.com domain was upgraded to SBS 2011?
Comment: An upgrade would keep the example.com domain name. As a matter of fact, you can actually choose another TLD, instead of .local, if you use an answer-file when installing SBS 2011. See http://blogs.technet.com/b/sbs/archive/2011/01/21/introducing-the-sbs-2011-answer-file-generator.aspx I'm using .lcl to avoid conflicts with OS X's Bonjour.

SBS domain name choice


How do I Read Bansuri Notation

Question: How do I read Bansuri Notation
Mumbai theme - A R Rahman
I know SA RE GA MA PA DHA NI SA, and the concept of low and high octaves.
How do I correlate the letters. And where are the letter different colors, i.e. Blue, Pink, or Red?
Answer: The notes in blue are to be played in the madhya sthāyi (middle octave), the notes in red in the mandara sthāyi (lower octave) and the notes in pink in the tāra sthāyi (upper octave).
I might add that it is not the standard practice to colour code the notation to indicate the octave. In Carnatic (south Indian classical) music, a dot above the note signifies the upper octave and a dot below the note signifies the lower octave; possibly the same notation is used in Hindustani (north Indian classical) music as well, but I am not completely certain.
I observe that the author of the notation has (in addition to the colour coding) used an apostrophe to indicate the octave of the note. So, 'N is the nishādam in the lower octave and R' is the rishabham in the higher octave.
Since you ask how to correlate the letters, I presume you mean how to correlate them with the natural rhythm of the song? The given notation is not very helpful in this regard. It ought to have been partitioned into sets of 4, at the very least.
You'll have to intuit this aspect, or obtain a better source of notation from elsewhere.

I'd also like to mention that the author of the notation has shifted the shadjam by a few notes. As the song starts you can hear the drone (shruti) in the background, which indicates the shadjam. When the flute begins, it is then clearly at the panchamam, and not the gāndhāram as in the given notation. So, the author of the notation has shifted the shadjam by a few notes down. This changes some things, for instance the ragam that the song is based on, etc. But, you ought to be able to play the song roughly in tune even with the given notation.

Edit (in response to the comments below):
The song naturally follows a rhythm that can be counted in cycles of 4 (or 8) units. So, I would notate the song with such indicators. For example, the first line could be better written as:

g,,g,,g,    g,,g,,r,    m,g,r,r,    s,'n,s,'n,

This is better than bunching the notes together without sufficient indicators, as in the given notation.
Comment: Thank you for your answer. What do you meay by `partitioned into sets of 4`? And when you say `shadjam`, you mean `sa`? `panchamam` for `pa, `gandharam` for `ga`?
Comment: Hi @Marium. Yes, *shadjam* is `sa`, *panchamam* is `pa`, etc. I've added an edit to the answer in response to your first query, since there seems to be some issue with the way comments are displayed. Feel free to ping me if anything is still unclear.

How do I Read Bansuri Notation


Determining 95% confidence interval of difference for proportion (Stata, or other)

Question: I have a dataset that is looking at completeness of data entry in a survey in two populations. Variables represent each category and are allocated 1 (present) or 0 (not present). I was wondering how to determine, if it is actually possible, a 95% confidence interval of difference for the proportion of completeness. This would help determine whether the difference in completeness (proportion) is statistically significant across the populations.
i.e. The first population for category 1 has a 70% completeness (seven presents and 3 not presents); the second population has 80% completeness (eight presents and 2 not presents). The difference in proportion is 10% (80-70), but what is the confidence interval (if available)?
Answer: In Stata, this can be done with the immediate versions of prtest. The immediate version obtains data from either group sizes and proportions or group sizes and success counts that are typed as arguments and not from the data stored in memory.
Here are the two ways of doing this:
. prtesti 10 .7 10 .8

Two-sample test of proportions                     x: Number of obs =       10
                                                   y: Number of obs =       10
------------------------------------------------------------------------------
    Variable |       Mean   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
           x |         .7   .1449138                      .4159742    .9840258
           y |         .8   .1264911                       .552082    1.047918
-------------+----------------------------------------------------------------
        diff |        -.1   .1923538                     -.4770066    .2770066
             |  under Ho:   .1936492    -0.52   0.606
------------------------------------------------------------------------------
        diff = prop(x) - prop(y)                                  z =  -0.5164
    Ho: diff = 0

    Ha: diff < 0                 Ha: diff != 0                 Ha: diff > 0
 Pr(Z < z) = 0.3028         Pr(|Z| > |z|) = 0.6056          Pr(Z > z) = 0.6972

. prtesti 10 7 10 8, count

Two-sample test of proportions                     x: Number of obs =       10
                                                   y: Number of obs =       10
------------------------------------------------------------------------------
    Variable |       Mean   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
           x |         .7   .1449138                      .4159742    .9840258
           y |         .8   .1264911                       .552082    1.047918
-------------+----------------------------------------------------------------
        diff |        -.1   .1923538                     -.4770066    .2770066
             |  under Ho:   .1936492    -0.52   0.606
------------------------------------------------------------------------------
        diff = prop(x) - prop(y)                                  z =  -0.5164
    Ho: diff = 0

    Ha: diff < 0                 Ha: diff != 0                 Ha: diff > 0
 Pr(Z < z) = 0.3028         Pr(|Z| > |z|) = 0.6056          Pr(Z > z) = 0.6972

In this case, you cannot reject the null that there's no difference in the proportion between the two groups. One caveat is that this is a large sample test, but you have very small sample sizes. Given these proportions, you would need a sample of almost 600 observations (compared to 20) for a two-sided alternative at 5% and equal size groups:
. power twoproportions 0.7 0.8, nratio(1) alpha(.05) test(chi2)

Performing iteration ...

Estimated sample sizes for a two-sample proportions test
Pearson's chi-squared test
Ho: p2 = p1  versus  Ha: p2 != p1

Study parameters:

        alpha =    0.0500
        power =    0.8000
        delta =    0.1000  (difference)
           p1 =    0.7000
           p2 =    0.8000

Estimated sample sizes:

            N =       588
  N per group =       294

One alternative would be to use Fisher's exact test, where the null is that the rows do not affect column outcomes, or that the two are independent. Here's how you can do that in Stata, though you have to specify the number of observations in each cell:
. tabi 7 3 \ 8 2, exact

           |          col
       row |         1          2 |     Total
-----------+----------------------+----------
         1 |         7          3 |        10
         2 |         8          2 |        10
-----------+----------------------+----------
     Total |        15          5 |        20

           Fisher's exact =                 1.000
   1-sided Fisher's exact =                 0.500

The p-values are very large for both the one-sided and two-sided tests, so we still cannot reject the null that the proportions are the same.


Javascript - Como passar parâmetros para uma função de um Event Attribute

Question: Não estou conseguindo fazer funcionar um código, onde crio uma função separadamente e chamo-a toda vez que quiser, porém mudando apenas os parâmetros. O javascript não executa

function minhaFuncao(num1, num2) {
    //codigo
}

variavel.onclick = minhaFuncao(num1, num2);

Como eu faço isso funcionar? Ele apenas funciona se eu escrevo o nome da função, sem os parâmetros, tipo:

variavel.onclick = minhaFuncao;

Porém eu gostaria de passar parâmetros para a função depois do "onclick".
OBS: Sem declarar a função logo após o onclick, quero que ela seja declarada anteriormente, só mude os parâmetros.
Answer: Quando você utiliza minhaFuncao(num1, num2);, o JavaScript interpreta que você está chamando a função e que deseja que ela seja executada, por isso não funciona dessa forma.
No seu caso, você precisa criar uma função anônima e dentro dessa função chamar uma outra (passando os parâmetros, claro).
Exemplo:
function minhaFuncao(num1, num2) {
    alert( num1 + num2 )
}

variavel.onclick = function() {
    minhaFuncao(10, 20);
}

Comment: Isso vale para `elemento.addEventListener` também.
Answer: Não sei se entendi como você deseja utilizar a função, mas esse é o comportamento esperado. Pense que o onClick funciona como um evento que pode ser disparado em vários momentos no código, mas você tem que passar os parâmetros quando chamar o evento. Por exemplo:

var Evento = {
  onClick: null
}

function soma(n1, n2){
  var sum = n1+n2;
  console.log("Soma: "+sum);
}

//Configura ação do evento - handler
Evento.onClick = soma;

//Usuário faz alguma ação e vc dispara o onClick
Evento.onClick(1,1);

//Usuário faz outra ação e vc dispara outro onClick
Evento.onClick(2,2);
Answer: Você pode utilizar o método bind()

var button = document.querySelector('button');
function minhaFuncao(num1, num2) {
  alert(num1 + num2);
}
button.onclick = minhaFuncao.bind(null, 2, 2);
<button>CLIQUE</button>

Referência

bind()


Curious habit, will I be late for work in n-days ? [Probability]

Question: Here is an interesting problem of probability :

Everyday, I can either go to work with a car or with the sub. If I
take the car, I will be late half of the time, whereas with the metro,
only a fourth (1/4 of the time). If today I'm late, tomorrow, I'll
change my way of commuting. So if one day I'm late using the car, the
next day I'll use the subway.
I start this habit tomorrow, and tomorrow I'll have a chance $p$ to
use the car.
1. What is the probability that I'm using the car the n-th day ?
2. What is the probability that I'm late on the n-th day ?

Here comes my answer. Can you please tell me if there are any mistakes ?
I ve set the event $C_n$ as taking the car on n-th day, $S_n$ for the sub.
$R$ is the event "being late".
The event $R^c$ is the contrary, beeing on time.
$$ P(C_n) = P( S_{n-1} \cap R ) + P( C_{n-1} \cap R^c )$$ by hypothesis.
$$ \begin{split}
P(C_n) = & P( S_{n-1} ) P ( R \vert S_{n-1}  ) + P( C_{n-1} ) P ( R^c \vert C_{n-1}  ) \\
 =& \frac 1 4 ( 1 - P( C_{n-1} ) ) + \frac 1 2 P( C_{n-1} ) \\
 =& \frac 1 4 ( P( C_{n-1} ) + 1 )
\end{split} $$
that because I can either take the car of the subway, so the two event $S_n, C_n$ are creating a partition for each day
(Can you maybe clarify this statement ? I don't know how to precisely justify this point ; This is for this equality : $1 - P( C_{n-1} ) =  P( S_{n-1} ) $).
Getting to this point, we recognise an arithmetico / geometrico sequence.
I think that we get this general expression :
$$ P(C_n) = (\frac 1 4)^n ( p- \frac 1 3 ) + \frac 1 3 $$
So this would be the answer to the first point, and for the second point, we simply have to use the formula of total probability :
$$ P( R) = P( S_{n} ) \frac 1 4 + P( C_{n} ) \frac 1 2 = \frac 1 4 ( 1 + P( C_n ))$$
Answer: Your argument is sound.  The equality you are worried about is find because you have to take either the car or the subway, so both sides are the probability you take the car.  I didn't check your solution to the recurrence, but it looks good.  It should converge to $\frac 13$ and it does.


Why is this statement Antisymmetric?

Question: Question
Let $S$ be a relation defined on $\mathcal{P}(\mathbb{N})$ by $XSY$ if and only if $X \subseteq Y$ and $|X| \equiv |Y|$(mod $2$).

My method
My thought process was that since Antisymmetry means that...
If $XSY$ and $YSX$ if and only if $Y = X$. Therefore, if $X \subseteq Y$ then $Y$ is not a subset of $X$. So the first part is True.
The second part however is where I am a little confused about.
If $|X| \equiv |Y|$ (mod $2$), then $|Y| \equiv$ $|X|$ (mod $2$). Thus making this not Antisymmetric. At least this is what I thought of at the time.
Upon checking the answers, the answer that was given states that this relation is Antisymmetric. But I can't figure out why.
Can anyone help me to understand this? Did I understand it incorrectly?
Comment: I am a bit confused. How does one define the cardinality mod 2 for infinite subsets of $\mathbb{N}$?
Answer: You want to prove the claim for two separate relations. It's however about one relation, namely the intersection of the two.
We can prove it more generally: if $R$ is antisymmetric ($x\,R\,y\,R\,x\implies x=y$) then so is $R\cap S$ for any relation $S$.
Proof: assume $x\,(R\cap S)\,y\,(R\cap S)\,x$, then because of the intersection, we must have $x\,R\,y\,R\,x$ as well, but that already implies $x=y$.

Why is this statement Antisymmetric?


correct primary key indexing

Question: Perhaps this is more of a DB/SQL question than Drupal. However, when defining large primary keys (multiple cols) how should I be indexing?
In my example below I am both setting a primary key -and- index on multiple cols. This is because I expect to use all of those cols in the WHERE part of queries. Is this correct?
<code>  $schema['tournament_stats_node'] = array(
    'description' => 'Stores relations between tournament stats and node.',
    'fields' => array(
      'entity_type' => array(
        'description' => 'Primary key: Entity type of participants, e.g. user/team.',
        'type' => 'varchar',
        'length' => 32,
        'not null' => TRUE,
        'default' => '',
      ),
      'nid' => array(
        'description' => 'Primary key: Related node ID',
        'type' => 'int',
        'not null' => TRUE,
        'unsigned' => TRUE,
        'default' => 0,
      ),
      'id' => array(
        'description' => 'Primary key: Unique entity ID',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'stat' => array(
        'description' => 'Tournament stat type',
        'type' => 'varchar',
        'length' => 32,
        'not null' => TRUE,
        'default' => '',
      ),
    ),
    'primary key' => array('entity_type', 'nid', 'id'),
    'indexes' => array(
      'entity_type' => array('entity_type'),
      'id' => array('id'),
      'nid' => array('nid'),
      'stat' => array('stat'),
    ),
  );
</code>
Answer: This is not a trivial question and you're actually asking multiple things :)
As mentioned by BetaRide, a technical, auto-generated key has the advantage that it is much simpler to maintain. The primary key defines how the data is stored and if you have a simple key then update/insert/delete should be a bit faster. What's better in general is a hard question to answer, you could make some comparisons (test both approaches, write 1 million rows and then compare update/delete/query speed)
For the indexes, you do most certainly not need a separate key per column. Some hints:

Only a single index can be used for a single query. Unless you will have queries which only have a condition on e.g. the id, that index is useless.
Indexes on multiple columns are read from left to right. E.g. a index on A,B,C can also be used for a query with conditions on A and B but not for one on B and C.
The more indexes you have, the slower are updates.

Same here, I recommend to fill your table with data and then use EXPLAIN to see how your queries are executed and which index they use. Then you can start to optimize things.
Answer: There's no reason to put fields in the primary key, just because you want to use a combination of these fields in queries. If the query is slow, use a normal index. Generally primary keys across multiple columns do ask for all sorts of trouble.
Comment: I'm pretty sure that's not correct. If it is then there are a lot of MySQL problems with D7 core...just take a look at (for example) the `field_data_*` tables which each have a primary key spanning **6** columns.
Comment: Nobody said that Drupal 7 core is perfect ;) And everyone who worked on it will tell you the opposite. Having a technical, auto-generated identifier is an often heard and not a bad suggestions, although it might not always make sense. This is also called a Technical/Surrogate key, see http://www.tonymarston.net/php-mysql/technicalkeys.html
Comment: But a table must have a primary key, so you are suggesting its better performance to have a 'serial' instead?
Comment: Yes. The primary Key should always be technical number without any business meaning.
Comment: Indeed, I thought the same.

correct primary key indexing


How to find $\int_0^1x^3$ using sums and partitions?

Question: The problem statement is to. Calculate $\int_0^1x^3dx$ by partitioning $[0,1]$ into subintervals of equal length.
This is my attempt:
Let $p=3.$ Let $\delta x = 0.5$ so that the partition is $[0,0.5],[.5,1]$ Then $\int_0^1x^3dx=\int_0^{0.5}x^3\cdot0.5+\int_{0.5}^1x^3\cdot0.5$ Which then becomes $$\Bigg[\lim_{n\to\infty}\dfrac{0.5-0}{n}\sum_{k=0}^{n-1}\Bigg(0+\dfrac{k}{n}(0.5-0)\Bigg)\cdot0.5\Bigg]+\Bigg[\lim_{n\to\infty}\dfrac{1-0.5}{n}\sum_{k=0}^{n-1}\Bigg(0.5+\dfrac{k}{n}(1-0.5)\Bigg)\cdot0.5\Bigg]$$
which reduces to
$$0.5\cdot\Bigg[\Bigg[\lim_{n\to\infty}\dfrac{0.5}{n}\sum_{k=0}^{n-1}\Bigg(\dfrac{k}{n}(0.5)\Bigg)\Bigg]+\Bigg[\lim_{n\to\infty}\dfrac{0.5}{n}\sum_{k=0}^{n-1}\Bigg(0.5+\dfrac{k}{n}(0.5)\Bigg)\Bigg]\Bigg]$$
or even better, it reduces to
$$0.5\cdot\Bigg[\lim_{n\to\infty}\dfrac{0.5}{n}\sum_{k=0}^{n-1}\Bigg[\Bigg(\dfrac{k}{n}(0.5)\Bigg)+\Bigg(0.5+\dfrac{k}{n}(0.5)\Bigg)\Bigg]\Bigg]$$
or
$$0.5\cdot\Bigg[\lim_{n\to\infty}\dfrac{0.5}{n}\sum_{k=0}^{n-1}\Bigg[\Bigg(\dfrac{k}{n}\Bigg)+0.5\Bigg]\Bigg]$$
$$0.5\cdot\Bigg[\lim_{n\to\infty}\dfrac{0.5}{n^2}\Bigg[\sum_{k=0}^{n-1}k+\sum_{k=0}^{n-1}0.5\Bigg]\Bigg]$$
which is
$$0.5^2\cdot\lim_{n\to\infty}\dfrac{1}{n^2}\Bigg(\dfrac{(n-1)(n)}{2}+\dfrac{n}{2}\Bigg)$$
$$0.5^2\cdot\lim_{n\to\infty}\dfrac{1}{2} = 0.25\cdot0.25 = 0.0625$$
But I know the integral $\int_0^1x^3=0.25$... What am I doing wrong here?
Comment: For example here $\int_0^1x^3dx=\int_0^{0.5}x^3\cdot0.5+\int_{0.5}^1x^3\cdot0.5$: why did you multiply by 0.5?. Same remark in the following with some divisions by $n$
Comment: $dx$ is not an actual value. It just represents a differential length. You can think of it as "summing over $x$"
Comment: @Damien Because the integrals had a $dx$ in them. For the sub integrals, I assumed $dx = 0.5$ as it went from $0$ to $0.5$ for the first one and $0.5$ to $1$ for the second one.
Comment: You don't need to first divide the segment by 2. Just directly divide it by $n$ ...
Answer: That's not what "using partitions" mean. It means to use the definition of the Riemann integral.
So, let $P_n=\left\{0,\frac1n,\frac2n,\ldots,1\right\}$. The upper sum with respect to this partition is\begin{align}\sum_{k=1}^n\frac1n\times\left(\frac kn\right)^3&=\frac1{n^4}\sum_{k=1}^nk^3\\&=\frac{n^4+2n^3+n^2}{4n^4}\\&=\frac14+\frac1{2n}+\frac1{4n^2}\end{align}whereas the lower sum is\begin{align}\sum_{k=1}^n\frac1n\times\left(\frac{k-1}n\right)^3&=\frac1{n^4}\sum_{k=0}^{n-1}k^3\\&=\frac{n^4-2n^3+n^2}{4n^4}\\&=\frac14-\frac1{2n}+\frac1{4n^2}.\end{align}Since$$\lim_{n\to\infty}\frac14+\frac1{2n}+\frac1{4n^2}=\lim_{n\to\infty}\frac14-\frac1{2n}+\frac1{4n^2}=\frac14,$$then$$\int_0^1x^3\,\mathrm dx=\frac14.$$
Answer: Since $n^3=6\binom{n+1}{3}+\binom{n}{1}$ we have $\sum_{n=1}^{N}n^3 = 6\binom{N+2}{4}+\binom{N+1}{2} = \frac{N^2(N+1)^2}{4}$. It follows that
$$ \int_{0}^{1}x^3\,dx = \lim_{N\to +\infty}\frac{1}{N}\sum_{k=1}^{N}\left(\frac{k}{N}\right)^3 = \lim_{N\to +\infty}\frac{N^2(N+1)^2}{4N^4}=\frac{1}{4}.$$
Since for any $m\in\mathbb{N}$ we have that $\sum_{n=1}^{N}n^m$ is a polynomial in the $N$ variable whose leading term equals $\frac{N^{m+1}}{m+1}$, the very same argument ensures that $\int_{0}^{1}x^m\,dx = \frac{1}{m+1}$.


The diophantine equation $\frac{1}{a}+\frac{1}{b}=\frac{n}{a+b}$

Question: How do I solve This diophantine equation $\dfrac{1}{a}+\dfrac{1}{b}=\dfrac{n}{a+b}$
of unknown $(a,b,n)\in \mathbb{(N^*)^3}$.
Comment: Please edit to include your efforts.
Comment: lulu I got to this point and didn't find any idea to continue the solution
for $a=b$ then $n=4$
Answer: This is equivalent to $\frac{(a+b)^2}{ab}=n$. So a solution satisfies $ab | (a+b)^2$ which means $a|b^2$ and $b|a^2$. Further, this implies that $a$ and $b$ have the same prime divisors. So let $p_1,\dots,p_k$ be such that $a=\prod_{i=1}^k p_i^{\alpha_1}$ and $b=\prod_{i=1}^k p_i^{\beta_i}$.
Computing $\frac{(a+b)^2}{ab}$ now gives $2+\prod_{i=1}^k p_i^{\alpha_i-\beta_i}+\prod_{i=1}^k p_i^{\beta_i-\alpha_i}$. Since this is supposed to be an integer, we must have $\alpha_i=\beta_i$ for all $1\leq i\leq k$, so $a=b$.
So the solution set is $\{(a,a,4):a\in \mathbb{N}\}$.
Comment: Thanks , Intuitively I came up with this solution but I thought I was wrong.
Comment: This question seems not to meet the standards for the site. Instead of answering it, it would be better to look for a good duplicate target, or help the user by posting comments suggesting improvements. Please also read the [meta announcement](https://math.meta.stackexchange.com/questions/33508/) regarding quality standards.


How does $\int \frac{1}{e^x +1} dx$ become $\ln{\big( \frac{1+e^x}{2} \big)} +1 -x $?

Question: I'm solving the equation $(1+e^x)yy'=e^{y}$ with the constraint $y(0)=0$. I've got pretty far but I'm struggling in the last part. I got stuck solving this integral: $$\int \frac{1}{e^x +1} dx $$ which is $x-\ln{|1+e^x|}$ but in order to satisfy the constraint I need to make it $\ln{\big( \frac{1+e^x}{2} \big)} +1 -x $.
How does $\int \frac{1}{e^x +1} dx$ become $\ln{\big( \frac{1+e^x}{2} \big)} +1 -x $?
Comment: Use the substitution $u=e^x$
Comment: did you integrate the other side of the equation too ? I mean the one with $y$
Answer: Let $u=e^x+1$ then $du=e^x dx$ or $du/(u-1)=dx$ so the integral becomes
$$\int \frac{1}{u(u-1)}du=\int \frac1u-\frac{1}{u-1}du.$$
Can you finish?
Answer: We have the differential equation:

$$(1+e^x)yy'=e^y\quad;\ y(0)=0$$

Separating the variables (and integrating):
$$\begin{align}
\int ye^{-y}\;\mathrm{d}y&=\int \frac{\mathrm{d}x}{(1+e^x)}\\[2ex]
-e^{-y}(y+1)&=\underbrace{\int \frac{\mathrm{d}x}{(1+e^x)}}_{\text{I}_2}\tag{integrating LHS by-parts}\label{1} \\[2ex]
\text{I}_{2}&=\int \frac{\mathrm{d}x}{(1+e^x)}\\[2ex]\\[2ex]
&=\int \frac{e^x\; \mathrm{d}x}{(e^x+e^{2x})}\\[2ex]
\text{Take $t= e^x$}\\[2ex]
\text{I}_2&=\int \frac{\mathrm{d}t}{t+t^2}\\[2ex]
&=\int \frac{\mathrm{d}t}{t(t+1)}\\[2ex]
&=\int \frac 1t -\frac{1}{t+1} \mathrm{d}t \\[2ex]
&=\ln\left(\frac{t}{t+1}\right)+C\\[2ex]
\implies\text{I}_2&=\ln\left(\frac{e^x}{e^x+1}\right)+C\\[2ex]
\implies -e^{-y}(y+1)&=\ln\left(\frac{e^x}{e^x+1}\right)+C\\[2ex]
y(0)=0\implies C&=\ln 2-1\\[2ex]
\implies e^{-y}(y+1)&=\ln\left(\frac{e^x+1}{2}\right)+1-x
\end{align}$$


React Native Router Flux: navigate from main scene to child

Question: Version

react-native-router-flux v3.35.0
react-native v0.31

I have few scenes. one of scenes have few sub-scenes. how can i navigate to one of sub-scenes from one of main scenes?
Example :
<Router createReducer={reducerCreate} getSceneStyle={getSceneStyle}>
        <Scene key="root">
          <Scene key="login" direction="vertical" component={Login} title="Login" hideTabBar hideNavBar />
          <Scene key="tabbar" initial={show}>
            <Scene key="main" tabs tabBarStyle={styles.tabBarStyle} tabBarSelectedItemStyle={styles.tabBarSelectedItemStyle} tabBarIconContainerStyle={styles.tabBarIconContainerStyle} >
              <Scene key="courses" component={Courses} title="Courses" icon={IconCourses} navigationBarStyle={styles.navigationBarStyle} titleStyle={styles.titleStyle} initial />
              <Scene key="register"  component={Register} title="Register" icon={IconRegister} navigationBarStyle={styles.navigationBarStyle} titleStyle={styles.titleStyle} />
              <Scene key="schedule" component={Schedule} title="Schedule" icon={IconSchedule} navigationBarStyle={styles.navigationBarStyle} titleStyle={styles.titleStyle} />
              <Scene key="evaluation" component={Schedule} title="Evaluation" icon={IconEvaluation} navigationBarStyle={styles.navigationBarStyle} titleStyle={styles.titleStyle} />
              <Scene key="profile"
              component={Profile}
              title="Profile"
              icon={IconProfile}
              navigationBarStyle={styles.navigationBarStyle}
              titleStyle={styles.titleStyle}
              onLeft={() => { Actions.login(); }}
              leftTitle="Add Account"
              onRight={() => { Actions.login({type: 'reset'}); }}
              rightTitle="Logout"
              rightButtonTextStyle={styles.ButtonTextStyle}
              leftButtonTextStyle={styles.ButtonTextStyle}
              leftButtonStyle={styles.leftButtonStyle} />
            </Scene>
          </Scene>
          <Scene key="terms" component={Terms} />
          <Scene key="details" component={Details} title="Details" navigationBarStyle={styles.navigationBarStyle} titleStyle={styles.titleStyle} backButtonTextStyle={styles.backButtonTextStyle} hideTabBar />
        </Scene>
      </Router>

I want to navigate from Details to Courses. but courses is a Tab under another. how can i do that?
I can navigate only to tabbar scene, not courses or register.
Comment: Did you try Actions.create to create the scenes prior to the render and pass it to the Router scenes prop? Also, try disabling any 'initial' props as that was causing issues for me.

What issue did you have with the Switch? I had a lot of trouble but sorted it out...  A trick that helped me force re-renders when Switch changed was setting Router key to something including part of the Switch state... ie authenticated vs guest... Make sure to change the key when the Switch changes. And don't forget about Actions.refresh. Seems hacky to me but seems to be used a lot as 'escape hatch'.
Answer: I've found that you can switch to inner tabs if you navigate to the tabbar first, e.g.:
<Button onPress={() => {
    Actions.tabbar({type:ActionConst.RESET});
    Actions.courses();
}} title="See Courses" />

The first scene transition resets the scene to your tab bar, and would by default show your initial scene, the second transition then replaces your current scene due to how react-native-router-flux handles tab scene transitions.
Comment: would you know how to pop back from a nested child to main scene?
Comment: How did you get to your nested child? Actions.pop() takes the current scene off the router stack...
If your tabs are not your main navigation scene, then you could try ActionConst.REPLACE to not clear your current router stack... (I've not tried that though...)
Comment: @HenryBevan So in a case where someone pops back after navigating, using your answer, would this take the person back to the scene where the button in your example was pressed?
Comment: @DanielBarde I don't think so - in my situation the 'tabbar' scene was the root scene, so there was never anything to pop back to after this navigation action.

Either way - the 'ActionConst.RESET' resets the view stack so the 'tabbar' becomes the root.
Answer: I actually answered a very similar question here. The problem is that from the context of login you'd have access to Actions.tabbar and it would then route you to either a nested scene with the initial prop set to true, or the first nested scene in the stack. To see an example of what I am talking about refer to the link I included in the first line of this answer.
Hope this helps! :)
Comment: Thanks for your answer. i know that. i can access from Details to tabbar. and when i access tabbar, first screen, Courses, is rendered. that's fine. problem is sometimes i need to navigate to other scene in tabbar not course. the solution is using switch function provided by router-flux but i couldn't get it to work. @brian-polonia


Reset file to specified commit in SmartGit

Question: How to reset file to specified commit in SmartGit? For example, I had created a commit and found that one file was wrongly changed, and I want to revert only that file.
Answer: Open the Log, navigate to the commit from which you want to resurrect the file, select the file in the Files view and invoke Save As from the context menu.
Answer: Another possibility: revert the whole commit with a wrongly changed file, but do not commit this change (select "Revert", not "Revert & Commit"). Then select all files except for the one you actually want to revert and discard the changes. Now you have this file in its original state in your working directory. You can commit it or modify it further.


Firefox vs. Firefox Mobile (Fennec): Are there javascript detectable differences?

Question: I've tried to find javascript elements that are supported by the mobile but not by the desktop version of Firefox or vice versa. I'm not interested in the user agent's differences. A difference between CSS support maybe helpful, too. Do you know a reliable way to detect differences?
Comment: @hello71 actually he mentioned above that he wasn't interested in ua sniffing. but you were too busy being the kewl brogrammer that you are. what exactly is called user agent? a user agent is software to be utilized by a user. if anyone has no clue what they're doing in web development, as well as in forums, it is you. YOU MEANT TO SAY USE FEATURE DETECTION. now you should say that 100x until you understand it. and you should also apologize to the owner.
Comment: @hello71 I know many discussions about pros and cons of browser sniffing. Sometimes it maybe useful, and sometimes not. Your comment is not helpful. Neither my question is answered nor you give an argument to underline your point of view.
Answer: -moz-touch-enabled CSS media query is only on mobile. there are a few more other mobile specific api's as well. https://developer.mozilla.org/en/Mobile/Firefox_Mobile_for_developers
Comment: Thank you. But this media query is implemented in the desktop version, too. It's only quite useless for desktops. Is there another chance, e.g. a bug, to detect Fennec easier or is a script available to determine viewport's settings/effect?
Comment: did you look at that link? it lists a number of mobile only apis
Comment: Yes, I've read the article but the mentioned APIs list CSS and viewport features only. They do exist in both - the mobile and the desktop - versions.


Abordagem otimizada de verificar se existe uma determinada entrada no arquivo hosts do Windows

Question: Possuo uma aplicação web Java com Applets que acessam serviços na web. Esses serviços são acessados através de um hostname específico (exemplo: services.webapp.com.br) configurado na aplicação. Sabendo que é a JVM do usuário que irá executar o código referente ao ciclo de vida dos Applets, cabe a essa JVM traduzir o host services.webapp.com.br em um endereço IP que será efetivamente utilizado pelos services.
Porém, pode acontecer do usuário editar seu Windows\System32\drivers\etc\hosts e redirecionar o host services.webapp.com.br para outro IP que não seja o endereço dos meus serviços, logo, a aplicação não conseguirá acessá-los e um erro acontecerá.
Sei que além do hosts do Windows existem outras formas de redirecionar o tráfego para um IP diferente, porém, quero cobrir esse ponto pois sei que meus usuários costumam utilizá-lo.
Em outras palavras, preciso saber em tempo de execução, se existe alguma entrada para o host services.webapp.com.br no arquivo hosts da máquina do usuário que está utilizando meu Applet, para exibir um alarme caso seja verdade. Existe uma forma elegante de fazer essa implementação?
Em algumas horas de busca no Google, vi que a única solução seria ler diretamente o conteúdo desse arquivo utilizando as bibliotecas de I/O do Java como neste exemplo, pois é algo de baixo nível do sistema operacional e foge do escopo do Java.
Desculpem pela não postagem de código, pois a minha maior dúvida está no conceito da implementação.
Comment: `(...) vi que a única solução seria ler diretamente o conteúdo desse arquivo utilizando as bibliotecas de I/O (...)` É isso mesmo. Qualquer outra solução que você encontre provavelmente faz exatamente isso por debaixo dos panos. `(...) é algo de baixo nível do sistema operacional e foge do escopo do Java (...)`. Experimente implementar isso em C ou Assembly antes de chamar a implementação em Java de baixo nível ;) e não, isso não foge em nada do escopo do Java. O framework e a linguagem foram feitos para casos como esse também.
Comment: Provavelmente eu acabe implementando por conta própria mesmo, pois fora a portabilidade entre os sistemas baseados em Mac, Windows e Linux, não vejo grandes desafios a ponto de haver uma grande mudança no tempo de desenvolvimento caso eu encontre um framework. Não chamei a implementação em Java de baixo nível, o que quis dizer foi basicamente que, levando em conta a portabilidade do Java e custo de manutenção, não sei se devo esperar que o Java possua bibliotecas (próprias ou de terceiros) para alterar um arquivo específico, de um sistema operacional específico.
Answer: Se me permite o comentário, esta é uma abordagem que pode ser considerada frágil. Um usuário mais experiente irá alterar as rotas diretamente no roteador e deixar o arquivo HOSTS intocado.
Algo mais seguro seria implementar um mecanismo de token encriptado que apenas os dois lados legítimos da aplicação poderiam interpretar. Assim, mesmo se o arquivo HOSTS for comprometido, o cliente só irá validar a conexão se um token válido for recebido.
Comment: Concordo com o ponto de vista à respeito da fragilidade, por isso utilizarei essa implementação apenas para troubleshooting e resoluções imediatas de problemas de conectividade, não utilizarei para basear o comportamento da minha aplicação. Achei sensacional a idéia do token, irei verificar se é possível implementar no servidor (administrado por outra equipe).


When does proving Tychonoff's theorem not require extensions of the ZF set theory?

Question: Proving Tychonoff's theorem requires the axiom of choice, in general. For Hausdorff spaces, just the Boolean prime theorem is enough. Is it possible to identify interesting classes of spaces or of index sets for which just the ZF framework is enough?
In particular, what happens (if anything noteworthy) for countably many Riemannian manifolds?
Of course, I am not interested in trivial answers (such as a finite number of non-empty spaces).
Comment: For locales, the theorem holds constructively.
Comment: @ziggurism I've been reading this claim quite a few times in the last couple of days, and it seems really interesting: can you point to any reference ?
Comment: Just a passing (irrelevant?) remark - which you probably know anyway, but just in case: Tychonoff implies the axiom of choice - i.e., Tychonoff is equivalent to the axiom of choice.
Comment: https://ncatlab.org/nlab/show/Tychonoff+theorem+for+locales
Answer: As an overview of how complicated the relation Tychonoff / AC is, see these papers which show that for other alternative definitions of compactness (which might be non-equivalent in the absence of AC) we see that the corresponding version of Tychonoff might or might not be equivalent to AC (or weaker versions). (See this paper for a comparison of the definitions themselves).
You don't need Tychonoff for a large class of spaces to prove the axiom of choice: the proof here shows that if we assume

The Tychonoff theorem holds for the class of all topological spaces $(X,\mathcal{T})$ such that $|\mathcal{T}| =4$ (which are obviously all compact)

Then full AC must already be true.
In ZF we can certainly show it for the class of all spaces with $|\mathcal{T}|= 2$  because then $X$ is indiscrete and any product of indiscrete spaces is indiscrete hence compact.
Maybe AC is already implied by Tychonoff for topologies of size 3? I think so, because it suffices (in the linked proof) to define the topology as $\{X_i, \{p_i\}, \emptyset\}$, I think, as @bof also noticed.
As to your countable case, this is much weaker. It might even be in ZF if your subclass of spaces (like Riemannian manifolds) is small enough. I'll let others be the judge of that. E.g. it might make a difference of the spaces are second countable and whether you want sequential compactness or other forms)
In summary: it's subtle.
Comment: For a countable product of finite spaces you need something like countable choice so I wouldn't be so sure
Comment: @bof I looked at that already and came to the same conclusion.
Comment: @Max it's provable in ZF that a countable product $\prod_n k_n$ with all $k_n $ integers, is compact.
Comment: @HennoBrandsma : that seems wrong. That means you can prove the compactbess theorem for predicate logic for countably many variables in ZF ? Can you link to a reference ? Or provide a proof ?
Comment: I meant propositional logic
Comment: @HennoBrandsma ah sorry you wrote "integers", I thought you meant finite sets ! Then it doesn't bother me so much, though I'm not sure either (but it would surprise me less)
Comment: @Max integers is essential, because they're already well-ordered.
Comment: @HennoBrandsma yes obviously that's the difference. I'll think about it and try to prove it myself for those (for finite sets I was completely lost haha)


Redirect to default node url

Question: I have an question about drupal's redirect.
Well I implemented hook_menu for the path: "node/%node/boost".
And I set all callbacks from default node path: "node/%node".
/**
 * Implements hook_menu().
 */
function my_module_menu() {
  $items['node/%node/boost'] = array(
    'title callback' => 'node_page_title',
    'title arguments' => array(1),
    'page callback' => 'node_page_view',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('view', 1),
  );

  return $items;
}

So I would get the node from my custom URL
but I got the redirect to default node URL like "node/123".
Any idea how can I load nodes from the my custom URL?
Thanks
UPD
If I change "page callback" function to the my custom function "my_module_page_view", for example:
/**
 * Callback.
 */
function my_module_page_view($node) {
  return 'Hello Drupal!';
}

I will see the text "Hello Drupal!" on the page with URL "/node/1/boost".
But if I use the next code:
/**
 * Callback.
 */
function my_module_page_view($node) {
  return node_view($node);
}

I will get redirect from "/node/1/boost" to "/node/1"
Comment: Are you saying that you visit node/123/boost, and you are redirected to node/123, or are you saying you want the user redirected from node/123/boost to node/123?
Comment: It happens. But I don't need it.
Comment: It seems the menu item didn't registered. Did you clear cache after adding this?
Comment: I would agree with @JimmyKo, but redirecting from node/1/boost to node/1 when node/1/boost didn't get registered is not the default behavior a plain installation of Drupal 7 has. If I create a node (whose ID is 1) and I visit node/1/random-long-string-no-module-uses, I am not redirected in any way. It could be you installed a module that redirects you when you try to access a non registered route like node/1/boost. That, added to the fact Drupal doesn't recognize node/%node/boost as route could explain the behavior you are noticing.
Comment: @kiamlaluno According to my memory, I remember that it would redirect **node/1/boost** to **node/1** if there is no node/1/boost router in the database. **boost** should become the second parameter of the page callback of **node/1** automatically.
Comment: @JimmyKo It doesn't redirect you: It shows the content of the page with the closer path. Redirecting would meant that the URL in the browser address bar would change from http://example.com/node/1/boost to http://example.com/node/1, but that doesn't happen, in Drupal 7 or earlier version.
Comment: Oh yes... `redirect` means the change on URL. Does @silvorezka misunderstand the meaning of `redirect` as I did?
Answer: Well It was a monkey's code in the one custom module: It implements hook_node_view() and, if the path  was similar to node/1/bla-bla, it redirected users to node/1.

Redirect to default node url


Como colocar tag html id com nome variável usando razor

Question: Oi, galera.
Uma dúvida bem boba, mas tá me dando muita dor de cabeça...
Tenho esse trecho de código html usando razor em asp net mvc, quero mesclar o id  desse trecho, tipo, "nomedoid + codigo que varia", como faço? Sei que é simples, mas não tô conseguindo...
 @relatorioDTO.Nome

Obrigada!
Comment: já tentou remover a aspas duplas da sua varável c#? Por exemplo: `@relatorioDTO.Nome`
Comment: Tentou usar o `@Html.Raw()`?
Comment: usei e funcionou!! vou atualizar meu post pra, de repente, puder ajudar alguém. Obrigada.
Comment: resolvi dessa forma: ` @Html.Raw("" + @relatorioDTO.Nome + "");`
Answer: Basicamente na sua view você pode fazer:
Segue um exemplo
Model
public class Fruta
{
    public int FrutaId { get; set; }
    public string NomeFruta { get; set; }
}

Controller
 public IActionResult Index()
    {
        var listaFruta = new List<Fruta>
        {
            new Fruta { FrutaId = 1, NomeFruta = "Pera" },
            new Fruta { FrutaId = 2, NomeFruta = "Uva" },
            new Fruta { FrutaId = 3, NomeFruta = "Maçã" },
            new Fruta { FrutaId = 4, NomeFruta = "Salada Mista" }
        };

        return View(listaFruta);
    }

View
@model IEnumerable<WebApplication1.Models.Fruta>

@{
    ViewData["Title"] = "Index";
}

Index

  Create New

            @Html.DisplayNameFor(model => model.FrutaId)

            @Html.DisplayNameFor(model => model.NomeFruta)

 @foreach (var item in Model) {

            @Html.DisplayFor(modelItem => item.FrutaId)

            @Html.DisplayFor(modelItem => item.NomeFruta)

}

Answer: Na verdade é realmente muito simples:

@relatorioDTO.Nome
Comment: verdade, várias formas de fazer!!!


Clickable Link to Header

Question: I'd like to have a header with PNG files, that are clickable.
I am using Drupal 7 and Omega Theme.
In the Omega default.css, I've added the following:
.branding-data {

    height: 250px;
    background-image: url('../images/slideheader1-object1441486291.png'),url('../images/slideheader1-object1068949429.png'),url('../images/slideheader1-object1159417376.png'),  url('../images/slideheader1.jpg');
        background-size: 100% 23.2%,49.55% 99.6%,39.51% 100%,  100%;
        background-position: 0px 192px,292px 4px,505px 0px,  0 0;
    background-repeat: no-repeat;}

It adds the images to my header. One of these should be a link to another page.
How can I do this?
Comment: Do you want to display clickable images in header of site?
Answer: answer found.
I've resolved this by adding new Blocks instead of background images:

Thereby adding Images, that are links to my header.
In the CSS files i then adjusted the position and opacity.
Greets,
Chris

Clickable Link to Header


Drupal 7 - How to apply Image Styles to a User uploaded logo for a theme

Question: I have need to be apply an Image Style setting to the logo uploaded at appearance/settings/THEME_NAME
Use Case is: The theme will be used across multiple unique instances within the organization and associated groups, each with different branding. The installation will be via an Install Profile including preset Image Styles.
The logo will need to be set by the individual installing the site.  It is a requirement that this individual will not need the skill to modify a tpl file in order to set the logo path/size or use any image editing software to modify the logo's dimensions pre upload.
... where to begin?
I suspect there are two routes:

Modify the existing logo field via page.tpl.php to use a predefined image style.
OR Add a new Image field to the Theme's settings form and calling that in page.tpl.php

Either task is pushing my Drupal ability so before I begin I thought I would ask for opinions on my assumed solutions above or better yet, actual solutions to setting image styles for the logo upload. :)
Thanks in advance,
Nick
Answer: You should be able to alter the logo-path in hook_preprocess_page and replace the logo path with the path of the transformed logo:
function mytheme_preprocess_page(&$variables) {
  $variables['logo'] = image_style_url('my_image_style', $variables['logo']);
}

Didn't try it out, but it should work somehow this way.
edit: there is a LOT of "logo" in my first sentence ;)
Comment: of course, I frequently under estimate the power of the preprocess!  Thanks I'll try it out and report back.  Cheers, Nick.
Comment: This gives me a bad path http ://styles/style_name/http/...
Answer: This is a design flaw in Drupal. Unfortunately, $logo is a bare HTTP URL, but there is no standard function available to convert a HTTP URL to the Drupal URI that the image_style_url function needs. However, you can convert the URL manually like this:
function mytheme_preprocess_page(&$vars) {
 $vars['logo']=image_style_url('my_image_style',str_replace($base_url.'/sites/default/files/','public://',$vars['logo']));
}

Please have a look at this and be aware that the solution above involves hard-coding (and is not very pretty).
Answer: I created a module Logo Image Style which lets you choose an image style for your site logo.
Logo Image Style:

Logo image style allows the site builder to use image styles to render the theme logo. The used image style can be set on a per theme basis.


Repetir LEFT JOIN com outros parâmetros na mesma consulta

Question: Tenho 2 tabelas:
PAI:
id
nome

FILHO:
id
idpai
sexo_filho

Queria fazer um SELECT que soma a quantidade de filhos homem e mulheres, aí que está o problema, eu só consigo fazer com um dos sexo:
SELECT pai.nome, count(distinct filho.id) as somahomem
FROM pai
LEFT JOIN filho ON pai.id = filho.idpai AND conta_filho.sexo = 'm'

Como fazer com os dois sexos? Ter o valor dos dois?
Answer: Você pode utilizar a cláusula CASE para contabilizar apenas uma condição. Veja o exemplo abaixo:
 SELECT
          PAI.NOME,
          COUNT(DISTINCT(CASE WHEN FILHO.SEXO = 'F' THEN FILHO.ID ELSE NULL END)) AS 'FEMININO',
          COUNT(DISTINCT(CASE WHEN FILHO.SEXO = 'M' THEN FILHO.ID ELSE NULL END)) AS 'MASCULINO'
 FROM
          PAI
          LEFT JOIN FILHO ON FILHO.ID_PAI = PAI.ID
 GROUP BY
          PAI.NOME

Veja funcionando no SQLFiddle
Comment: Valeu, ta indo certinho, não tem como colocar um distinct nele?
Comment: Nessa estrutura que você informou, ao meu ver, é desnecessário o distinct pois o resultado seria o mesmo.
Comment: Então, minha consulta é mais complexa, tem vários count e sum com outras tabelas.

Sem o distict não sei porque ele vai multiplcando os counts entre eles....
Comment: Atualizei com o DISTINCT.
Answer: Você pode usar mais de um JOIN:
SELECT pai.nome,
    count(distinct filho.id) as somahomem,
    count(distinct filho2.id) as somamulher
FROM pai
    LEFT JOIN filho ON pai.id = filho.idpai AND filho.sexo = 'm'
    LEFT JOIN filho2 ON pai.id = filho2.idpai AND filho2.sexo = 'f'
GROUP BY
    pai.nome;

Answer: Pode utilizar o SUM() com IF()
SELECT
  pai.nome,
  SUM(if(filho.sexo = 'm', 1, 0)) as somahomem,
  SUM(if(filho.sexo = 'f', 1, 0)) as somamulher
FROM
  pai
  LEFT JOIN filho ON (pai.id = filho.idpai)
GROUP BY pai.id