Extract OLE object data in Microsoft Office without OLE application

Question: Is it possible to extract the content of an embedded OLE object in Microsoft Office using VBA/VSTO? I am talking about a situation where the application with which the OLE object was created is not available. In this case some sort of converter application could make use of the raw data.
For instance, in Excel the object is accessible via ActiveSheet.Shapes(x).OLEFormat but I have not found a way to retrieve the raw data of the object.
One way would be to open the native file (Office Open XML/Compound File) and extract the data from there. But maybe there is a simpler approach?
Comment: You can copy it to a clipboard and then use VSTO to paste it from the clipboard. I haven't tested that, but it's worth a try. Let me know how it works out.
Comment: Good idea. Copying the shape and then accessing `Clipboard.GetData("Embedded Object")` does the trick. Thanks!
Comment: Cool, I'll post it as an answer so I can get credit for it. I'm working on the same thing right now but need to do it in VBA, much more difficult that way :(.
Answer: Copy the OLEObject to the clipboard then get it from the clipboard, e.g. something like this in VSTO:
Dim ole as OLEObject
...
ole.Copy
...
Clipboard.GetData("Embedded Object")

In VBA I have just been opening a folder through Shell then pasting using SendKeys.
ole.copy
Shell "explorer.exe " & sFolderName, vbNormalFocus
Application.Wait Now() + TimeSerial(0, 0, 3)
Application.Sendkeys "^v"

Answer: Copy the OLEObject to the clipboard, then get it over "Shell.Application" (verb Paste) from the clipboard to folder
 For Each Sh In Sheet1.OLEObjects
  If InStr(1, Sh.Name, "Object", 1) Then
   Sh.Copy
   ' this code paste Embedded Object to folder
   CreateObject("Shell.Application").Namespace("c:\temp\!").Self.InvokeVerb "Paste"
  End If
 Next Sh

Answer: I approached this another way (non-VBA).

Rename the document/spreadsheet to .zip (eg instead of .docx)
Open the .zip and browse the structure to the embedded objects eg \word\embeddings

Edit the .bin file(s) (eg in Notepad++) - you should be able to identify the file extension in the first 10 lines

Now strip all the header/junk from the start of the file - search for ÐÏࡱ and remove everything before/above it

The beginning of the file will now look like this:

Save the file with the extension that you identified above
The file should open and function correctly


How to use MediaScannerConnection scanFile to scan a file in android

Question: How to scan a file which has downloaded from web ? I have successfully downloaded the file from url and save it into Folder but When I open media player there are no media. After little bit search I just saw the posts that after downloading the file, It has to scan. so I have tried something like this
public class TagsPlugin extends CordovaPlugin {

    private CallbackContext callbackContext;
    private static Context context;
    private MediaScannerConnection conn;

    @Override
    public boolean execute(final String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
        this.callbackContext = callbackContext;

        final String songName = args.getString(0) + " " + myDomain;

        cordova.getActivity().runOnUiThread(new Runnable() {

            public void run() {
                    String resp;

                    final MediaScannerConnection conn;
        final String newFilePath = action;

                    String filePath = action;
                    AudioFile audioFile = null;
                    Tag audioTag = null;
                    AudioHeader audioHeader = null;

                    try{
                        TagOptionSingleton.getInstance().setAndroid(true);
                        AudioFile f = (MP3File) AudioFileIO.read(new File(filePath));
                        audioTag = f.getTag();

                        audioTag.setField(FieldKey.TITLE, songName);

                        f.commit();

                        resp = audioTag.getFirst(FieldKey.TITLE);

File file = new File(filePath);
MediaScannerConnection.scanFile(context, new String[] { file.getAbsolutePath() }, null, null);
//MediaScannerConnection.scanFile(context, new String[] { filePath }, null, null);

                    }catch (Exception e){
                        StringWriter errors = new StringWriter();
                        e.printStackTrace(new PrintWriter(errors));
                        resp = errors.toString();
                    }

                    PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, resp);
                    pluginResult.setKeepCallback(true);
                    callbackContext.sendPluginResult(pluginResult);

                }

        });

        return true;

    }
}

but it's showing the below errors
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.content.Context.bindService(android.content.Intent, android.content.ServiceConnection, int)' on a null object reference
    at android.media.MediaScannerConnection.connect(MediaScannerConnection.java:119)
    at android.media.MediaScannerConnection.scanFile(MediaScannerConnection.java:238)
    at TagsPlugin$1.run(TagsPlugin.java:91)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5221)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

What am i doing wrong ? I just want to display the downloaded songs in media player in android.
Is there any phonegap/cordova plugin which do the same as i am doing ?
Answer: I've done by myself using below code.
MediaScannerConnection.scanFile(this.cordova.getActivity(),
                      new String[] { filePath }, null,
                      new MediaScannerConnection.OnScanCompletedListener() {
                  public void onScanCompleted(String path, Uri uri) {
                      cbContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, uri.toString()));
                  }
            });


Linear regression property

Question: Suppose that I have the following model:

$y_i = \beta_0 + \beta_1 x_{1i} + \beta_2 x_{2i} + u_i$

where $\hat{\beta_k}$, k=0,1,2 ,  are estimated by the method of least squares, using a sample of size n.

How can I show that if $z_i =a_0 + a_1 x_{1i} + a_2 x_{2i} $, where $a_k$ are constants, then:
$\sum_{i=1}^n z_i(y_i-\hat{\beta_0} - \hat{\beta_1} x_{1i} - \hat{\beta_2} x_{2i})=0$
  ?

My attempt was to try to expand and compare to the first order condition: $\sum_{i=1}^n (y_i-\hat{\beta_0} - \hat{\beta_1} x_{1i} - \hat{\beta_2} x_{2i})=0$, but things got messy and lead to nowhere.
Answer: You are minimizing the following function
$$
\arg \min S(\beta)=\arg\min\sum ( y_i - \beta_0 - \beta_1x_{1i} - \beta_2x_{2i} ) ^2
$$
From the F.O.C you have the following equation
$$
\sum(y_i - \hat{\beta}- \hat{\beta}_1x_{1i}-\hat{\beta}_2x_{2i})=0
$$
$$
\sum x_{1i}(y_i - \hat{\beta}- \hat{\beta}_1 x_{1i}-\hat{\beta}_2x_{2i})=0
$$
$$
\sum x_{2i}(y_i - \hat{\beta}- \hat{\beta}_1x_{1i}-\hat{\beta}_2 x_{2i})=0
$$,
now, multiple eq. (1) by $\alpha_0$, eq. (2) by $\alpha_1$ and eq. (3) by $\alpha_3$ and add them up
$$
\sum(\alpha_0 + \alpha_{1}x_{1i} + \alpha_2 x_{2i})(y_i - \hat{\beta}- \hat{\beta}_1 x_{1i}-\hat{\beta}_2 x_{2i})=0 .
$$

Linear regression property


Error: Emit attempted before Angular Webpack plugin initialization(Error: Emit attempted before Angular Webpack plugin initialization)

Question: Here what im doing is I have created new project in Angular 15 and moving the code from the Angular version 5. I have fixed all the errors but stuck with this one error.And also here is the my current Angular version details:
Angular CLI: 15.2.10
Node: 18.18.2
Package Manager: npm 10.2.0
OS  : win32 x64
I'm getting below error:
[Error]: https://i.stack.imgur.com/22xkl.png
Here is package.json file:
<code>{
  "name": "demo",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "prod": "node --max_old_space_size=4096 node_modules/@angular/cli/bin/ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "build-prod": "node --max_old_space_size=5048 ./node_modules/@angular/cli/bin/ng build --
     prod"

  },
  "private": true,
  "dependencies": {
    "@agm/core": "^1.0.0-beta.3",
    "@angular/animations": "^15.0.0",
    "@angular/common": "^15.0.0",
    "@angular/compiler": "^15.0.0",
    "@angular/core": "^15.2.10",
    "@angular/forms": "^15.0.0",
    "@angular/platform-browser": "^15.0.0",
    "@angular/platform-browser-dynamic": "^15.0.0",
    "@angular/router": "^15.0.0",
    "@ngtools/webpack": "^14.2.3",
    "@ngui/datetime-picker": "^0.16.2",
    "@progress/kendo-angular-charts": "^3.8.0",
    "@progress/kendo-angular-common": "^3.2.1",
    "@progress/kendo-angular-dropdowns": "^3.5.2",
    "@progress/kendo-angular-intl": "^1.7.0",
    "@progress/kendo-angular-l10n": "^1.3.0",
    "@progress/kendo-angular-pdf-export": "^1.3.1",
    "@progress/kendo-drawing": "^1.17.1",
    "@progress/kendo-licensing": "^1.2.2",
    "@syncfusion/ej2-angular-richtexteditor": "^17.4.40",
    "@types/angular-ui-bootstrap": "^0.13.44",
    "@types/d3": "^5.7.2",
    "@types/jquery": "^3.3.29",
    "@types/jqueryui": "^1.12.7",
    "@types/underscore": "^1.8.14",
    "admin-lte-css": "^2.4.3",
    "angular-checklist": "^1.3.0",
    "angular-sortablejs": "^2.7.0",
    "angular2-datetimepicker": "^1.1.1",
    "angular2-image-zoom": "^1.2.1",
    "angular2-json2csv": "^1.1.2",
    "angular2-tag-input": "^1.2.3",
    "babel-regenerator-runtime": "^6.5.0",
    "bootstrap": "^3.4.1",
    "bootstrap-css-only": "^3.3.7",
    "chart.js": "^2.9.4",
    "core-js": "^2.6.5",
    "d3": "^5.9.2",
    "font-awesome": "^4.7.0",
    "hammerjs": "^2.0.8",
    "html2canvas": "^1.0.0-rc.1",
    "ionicons": "^2.0.1",
    "jquery": "^3.6.0",
    "jquery-ui-sortable": "^1.0.0",
    "jqueryui": "^1.11.1",
    "jspdf": "^1.5.3",
    "lodash": "^4.17.21",
    "moment": "^2.24.0",
    "ng-pick-datetime": "^5.2.6",
    "ng-pick-datetime-moment": "1.0.7",
    "ng-recaptcha": "^5.0.0",
    "ng-starrating": "^1.0.11",
    "ng2-charts": "^1.1.1",
    "ng2-ckeditor": "1.1.9",
    "ng2-nouislider": "^1.7.13",
    "ng2-order-pipe": "^0.1.5",
    "ng2-pdf-viewer": "^5.0.1",
    "ng2-search-filter": "^0.4.7",
    "ng2-toastr": "^4.1.2",
    "ng2-tree": "^2.0.0-rc.11",
    "ngx-bootstrap": "^2.0.0-beta.9",
    "ngx-color-picker": "^4.5.3",
    "ngx-editor": "^1.2.1",
    "ngx-embed-video": "^1.0.4",
    "ngx-inactivity": "^1.0.1",
    "ngx-pagination": "^3.2.1",
    "ngx-stripe": "^6.0.0",
    "ngx-toastr": "^6.4.1-beta.0",
    "ngx-ui-switch": "^1.6.0",
    "npm": "^7.24.2",
    "primeng": "^4.3.0",
    "rxjs": "~7.5.0",
    "rxjs-compat": "6.2.2",
    "save": "^2.3.3",
    "socket.io-client": "^2.2.0",
    "sortablejs": "^1.8.4",
    "tslib": "^2.3.0",
    "underscore": "^1.13.1",
    "uuid": "^9.0.1",
    "zone.js": "~0.12.0"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^15.0.5",
    "@angular/cli": "^15.2.10",
    "@angular/compiler-cli": "^15.0.0",
    "@angular/language-service": "^5.0.0",
    "@types/googlemaps": "^3.38.0",
    "@types/jasmine": "~4.3.0",
    "@types/jasminewd2": "^2.0.6",
    "@types/node": "^6.0.118",
    "@types/socket.io-client": "^1.4.32",
    "codelyzer": "~3.2.0",
    "jasmine-core": "~4.5.0",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~6.4.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-cli": "~1.0.1",
    "karma-coverage": "~2.2.0",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~5.1.0",
    "karma-jasmine-html-reporter": "~2.0.0",
    "mi18n": "^0.3.4",
    "protractor": "^7.0.0",
    "ts-node": "~3.2.0",
    "tslint": "~5.7.0",
    "typescript": "~4.8.0"
  }
}

Here is angular.json file:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "demo": {
      "projectType": "application",
      "schematics": {},
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/demo",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": [
              "zone.js"
            ],
            "tsConfig": "tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css",
              "node_modules/bootstrap-css-only/css/bootstrap.min.css",
              "node_modules/font-awesome/css/font-awesome.css",
              "node_modules/ionicons/css/ionicons.css",
              "node_modules/admin-lte-css/dist/css/AdminLTE.css",
              "node_modules/admin-lte-css/dist/css/skins/_all-skins.css",
              "src/assets/kendoui.css",
              "src/assets/sass/form-builder.scss",
              "src/assets/sass/form-render.scss",
              "node_modules/ng2-toastr/bundles/ng2-toastr.min.css",
              "node_modules/primeng/resources/primeng.min.css",
              "node_modules/primeng/resources/themes/omega/theme.css",
              "node_modules/ng2-tree/styles.css"
            ],
            "scripts": [
              "node_modules/jquery/dist/jquery.min.js",
              "node_modules/jquery-ui-sortable/jquery-ui.min.js",
              "node_modules/bootstrap/dist/js/bootstrap.min.js",
              "node_modules/moment/min/moment.min.js",
              "node_modules/chart.js/dist/Chart.js",
              "src/assets/dist/js/adminlte.js",
              "src/assets/hammerjs/hammer.js",
              "node_modules/jspdf/dist/jspdf.min.js",
              "node_modules/html2canvas/dist/html2canvas.min.js"
            ]
          },
          "configurations": {
            "production": {
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "500kb",
                  "maximumError": "1mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "2kb",
                  "maximumError": "4kb"
                }
              ],
              "outputHashing": "all"
            },
            "development": {
              "buildOptimizer": false,
              "optimization": false,
              "vendorChunk": true,
              "extractLicenses": false,
              "sourceMap": true,
              "namedChunks": true
            }
          },
          "defaultConfiguration": "production"
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "configurations": {
            "production": {
              "browserTarget": "demo:build:production"
            },
            "development": {
              "browserTarget": "demo:build:development"
            }
          },
          "defaultConfiguration": "development"
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "demo:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "polyfills": [
              "zone.js",
              "zone.js/testing"
            ],
            "tsConfig": "tsconfig.spec.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          }
        }
      }
    }
  },
  "cli": {
    "analytics": "125d0ec8-f37c-4580-834c-591ee3bb8c6c"
  }
}
Here is tsconfig.json
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "ES2022",
    "module": "ES2022",
    "useDefineForClassFields": false,
    "lib": [
      "ES2022",
      "dom"
    ]
  },
  "include": [
    "node_modules/angular2-json2csv/src/csv.service.ts",
    "node_modules/ngx-inactivity/src/app/ngx-inactivity/index.ts",
    "src/main.ts",
    "src/polyfills.ts",
    "src/*.ts",
    "src/app/**/*.ts"

    ],
  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": true,
    "enableIvy": false
  }
}
Here is tsconfig-app.json:
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": []
  },
  "files": [
    "src/main.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ],
  "angularCompilerOptions": {
    "enableIvy": false
  }
}

Here is tsconfig-spec.json:
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/spec",
    "types": [
      "jasmine"
    ]
  },
  "include": [
    "src/**/*.spec.ts",
    "src/**/*.d.ts"
  ]`enter code here`
}

Here need solution for this issue.Thanks in advance
</code>
Answer: Bro, I suggest you do the following steps, As per my perception you are trying to update from angular version 5 to angular version 15 with ng update, this might not be a feasible solution, so try following the below steps

Create a new angular app with angular version 15
Take a backup of existing project code except discarding node modules
Now replace the src folder,add all the third-party dependencies in
package.json, and add scripts or styles  in the angular.json from the
existing  project   in the newly created angular project
Now run 'npm i'
You might be getting some third-party dependencies version issues, then try
to update third-party dependencies as well, then rerun 'npm i'

Keeping angular 5 to date is not a good practice, try to update angular
once one or two years
I hope the above steps help you
Stay Safe, Happy Coding.
Comment: No it is not working still getting same error..
./src/main.ts - Error: Module build failed (from ./node_modules/@angular-devkit/build-angular/node_modules/@ngtools/webpack/src/ivy/index.js):
Error: Emit attempted before Angular Webpack plugin initialization.

Error: Failed to initialize Angular compilation - NGCC failed.
Comment: Downgrade the typescript version to 4.8.0  "typescript": "~4.8.0", delete the   package.lock.json, file then npm i, and then try to run
Comment: After doing all these i'm still getting the same error:

./src/main.ts - Error: Module build failed (from ./node_modules/@angular-devkit/build-angular/node_modules/@ngtools/webpack/src/ivy/index.js):
Error: Emit attempted before Angular Webpack plugin initialization.

Error: Failed to initialize Angular compilation - NGCC failed.


Waldorf Blofeld keyboard: installing "standard samples"

Question: I'm not sure that this StackExchange is the best place for this, so close this question with extreme prejudice if I'm out of line.
I have a Waldorf Blofeld keyboard, and via their "Spectre" application on Windows I'm trying to download (or upload; however you want to look at it) the "Standard Sample" set from the computer to the device. The software seems to start transferring the file (a MIDI file), and the device UI displays a message to the effect that the contents are being downloaded.
However, after getting to (variously) 3% or 4% of the transfer (according to Spectre), the transfer just stops. The little red "MIDI" light at the top of the keyboard UI stops flashing as well.
I've left it sitting there in that state for long periods of time (hours), and nothing ever happens.
Now, I've been able to do firmware updates and patch file transfers from the same computer with the same setup without any problems. And in all other ways, the keyboard seems to work just fine; it plays music and stuff.
Is there some sort of "reset" or something that can/should be done to prep the sample memory for a download?
I'm running the 1.22 version of the firmware, and (I think) a new version of Spectre; I just re-downloaded it and re-installed it today.
Comment: http://www.waldorf-music.info/en/license-sl-sample-option-en-kb ?
Comment: @Patrx2 I have a Blofeld **Keyboard**, which does not require the SL license. Thanks for responding however.
Comment: OK, just saw that and wondered, hence the question mark.
Comment: @Patrx2 my dirty secret is that it's not really a Windows machine; it's a Windows VM on a Linux host. My next step is to try a real native Windows host for the download. I would not be surprised if the USB driver-to-driver stuff is screwing things up.
Comment: Everything else works from the virtual Windows however, like patch loading etc.
Comment: Do they have any kind of tech support?
Comment: Yes, I'm working through the "make sure the unit is plugged into the wall" phase of the interaction :)
Comment: Hehehe! Way back in the day, I worked in Microsoft tech support when Digital Equipment Canada handled it. It was more "Let's get the first question out of the way: you're getting light on power LEDs on your system, yes? Right. Now, what we're going to do..." All n00bs in tech support these days. :P
Answer: I don't know whether this constitutes a helpful answer for any future sufferer of my problems, but here's the status:

The "Standard Sample Set" is really two downloads. One download is a MIDI file (the one I had), and one is a "wpc" file. I don't know what "wpc" means but that's the one you really want.
The "wpc" file is loaded via the Spectre app in the "Program" part of the application view (the stuff on the left). When you open the "wpc" file, you'll see all the samples listed in that panel. Then you click "Transmit" to send them to the Blofeld. That process takes like 20 minutes. It may or may not be the case that the "wpc" file must be loaded first. All I know is that started working before the MIDI file load worked. For me.
For whatever reason, my original PC succeeded in that but did not succeed in transmitting the MIDI file for the samples. Now, I will point out that I have no idea what the MIDI file is supposed to actually do.
I installed Windows 10 on another old laptop I have and was able to install the MIDI file from there. I still don't know whether that did anything useful or interesting.
I can see that the samples are there. When cycling through the "Shape" values available for an oscillator, you get through a zillion "Wavetable" values and then you get to the samples. The samples seem to be pretty good, though if you try them out in a random patch weird things can happen for reasons I don't understand; I think the way the oscillator software iterates through the samples doesn't necessarily work the same as the way the wavetable entries work, so sometimes settings in the patch may cause things to go off the rails. I would love for somebody who gets it to explain what's going on.

Thus and all, I think I've done what I want, though I'm not entirely sure I see the point. The Blofeld is extremely flexible with its "native" analog simulation self, and the samples seem like an add-on that might enable some useful effects but musically I'm not so sure. (I'd love to be proven wrong of course.)
For reference, the Blofeld stuff is available here, for now at least.


Why do we need importance sampling?

Question: Let's say we want to calculate the following expectation:
$$
\mathbb{E}_{z\sim p_z(z)}[f(z)]
$$
One issue, is that the samples from $p_z(z)$ could be not very informative:

We see here that $f(z)$ only takes on non-zero values near the edges of $p_z(z)$.
We we can solve this by using importance sampling, which will take more samples from regions with non-zero contribution.
What I don't understand is why we would want to use importance sampling. I.e., the samples of $z$ that cause $f(z)$ to be zero are going to drag down the expectation towards zero, which seems good since indeed, for most values of $z$, $f(z)$ will be zero.
Note, I'm assuming that the expectation is a single value and roughly, the expression means: "The expected value of $f(z)$ when we randomly sample from $p_z(z)$ is $E$", where $E$ is a single number.
Comment: The main motivation of importance sampling is mainly that you cannot sample from the real distribution, but you can sample from the constructed one.
Answer: Importance sampling returns an unbiased estimate of the expectation of interest, $E$ say, for all valid importance densities $q$. The choice of $q$ is driven by (i) the possibility to simulate from $q$, (ii) the ability to compute the importance ratio $f(\cdot)p_z(\cdot)/q(\cdot)$, and (iii) a reduced variance${}^\star$ of the Monte Carlo estimate,
$$\widehat E = \frac{1}{n}\sum_{i=1}^n f(z_i) \frac{p_z(z_i)}{q(z_i)}\qquad z_i\stackrel{\text{iid}}{\sim} q\tag{1}$$
which means $q(\cdot)$ must be as similar as possible to $|f(\cdot)|p_z(\cdot)$, which formally is the optimal choice, albeit of no use since it requires the value of $E$.
Avoiding the kernel of $f$, i.e., the region of the space $\mathfrak X$ where$$f(z)=0$$is a good thing for estimating $E$, because this reduces the variance (e.g., in not producing a random number of zeroes in the Monte Carlo estimate), while not inducing bias. In other words, since
$$\int f(z)p_z(z)\,\text dz=\int f(z)\mathbb I_{f(z)\ne 0}p_z(z)\,\text dz+\underbrace{\int f(z)\mathbb I_{f(z)=0}p_z(z)\,\text dz}_{\text{equal to }0}$$
using a random variable to approximate the second term is creating unnecessary noise.
For instance, take the ideal case of an arbitrary density $q(\cdot)$ that is positive everywhere and consider $q^+(\cdot)$, its truncation  to the support of $f(\cdot)$, i.e.,
$$q^+(x) = \dfrac{q(x)\mathbb I_{f(x)\ne 0}}{\int q(z)\mathbb I_{f(z)\ne 0}\text dz}\stackrel{\text{def}}{=}\dfrac{q(x)\mathbb I_{f(x)\ne 0}}{\mathfrak Q(f(X)\ne 0)}$$
as an alternative (valid) importance density. (I assume for comparison sake that $\mathfrak Q(f(X)\ne 0)>0$ can be computed exactly.)
The importance Monte Carlo estimator associated with $q^+(\cdot)$ then writes as
$$\frac{1}{n}\sum_{i=1}^n f(z_i) \frac{p_z(z_i)}{q^+(z_i)}\qquad z_i\stackrel{\text{iid}}{\sim} q^+$$
which can be rewritten as
$$\frac{\mathfrak Q(f(X)\ne 0)}{n}\sum_{i=1}^n f(z_i) \frac{p_z(z_i)}{q(z_i)}\qquad z_i\stackrel{\text{iid}}{\sim} q^+\tag{2}$$
to compare with (1), which also writes as
$$\frac{M}{n}\frac{1}{M}\sum_{i=1}^M f(z_i) \frac{p_z(z_i)}{q(z_i)}\qquad z_i\stackrel{\text{iid}}{\sim} q^+$$
where$$M\sim\mathcal Bin(n,\mathfrak Q(f(X)\ne 0))$$is the random number of simulations $z_i$ from $q$ (out of $n$) such that $f(z_i)\ne 0$, which are then simulations from $q^+$. One can spot two sources of additional variability in (1), against (2):

The random ratio $\frac{M}{n}$ has expectation $\mathfrak Q(f(X)>0)$ and variance$$\mathfrak Q(f(X)\ne 0)\mathfrak Q(f(X)=0)/n$$
(1) is based on less simulated random variables than (2), meaning that the variance of the empirical average is $n/M$ times larger for (1), compared with (2).

${}^\star$It is important to remind readers that some importance functions $q$ lead to infinite variance solutions for pairs $(f,p_z)$.
Answer: So long as importance sampling is done correctly, it always give an unbiased estimator for the true integral of interest --- this occurs irrespective of the generative distribution you use in the method, so long as it meets the basic requirements.  So the main remaining issue of concern is the variability of the estimator.  As a general rule, the closer the kernel of the generative distribution is to the integrand in the integral (i.e., to the function $x \mapsto f(x) p_X(x)$) the lower the variability of the estimator.  That is largely the point of importance sampling.
Answer: The short version is that there are two different reasons why we might use importance sampling.  First, importance sampling is useful if we don't know how to sample from $p_z(z)$.  Second, it is also useful in the situation you draw, where $f(z)$ has very large peaks in the tail of $p_z(z)$; it gives us a more accurate estimate of the expectation.  These are two different motivations why we might use importance sampling.  Both are valid.  I'll explain below in depth.

Before I jump into the details of your question, let me start with some background, namely, the standard setting that motivates importance sampling.  The standard setting is that we wish to estimate
$$\mathbb{E}_{z \sim p_z(z)}[z],$$
but we do not have a way to sample from $p_z(z)$.  Since we don't have any way to sample from $p_z(z)$, there is no way to use the standard estimator for the mean (drawing a few samples from the distribution and then computing the sample average), so we need some other way to estimate this expectation.
Importance sampling gives us a solution to this problem.  Importance sampling allows us to pick a distribution $q(z)$ that we do know how to sample from, and then estimate the expectation above by choosing samples distributed according to $z$.  In particular, it uses the fact that
$$\mathbb{E}_{z \sim p_z(z)}[z] = \mathbb{E}_{z \sim q(z)}\left[{z p_z(x) \over q(z)}\right].$$
Notice that we do have a way to estimate the right-hand side using standard methods, by drawing samples from $q(z)$, as long as we have a way to compute $p_z(z)$ for any given $z$.  There are many situations where we do know how to compute $p_z(z)$ for any given $z$ of interest, but we don't know how to efficiently draw a random sample from the distribution $z \sim p_z(z)$.

Now, your question asks about a slightly different situation.  The above exposition talks about computing $\mathbb{E}[z]$, but your question asks about $\mathbb{E}[f(z)]$, which is slightly different.  So now let's address your specific question.  Why do we use importance sampling for this task?  The answer is: it depends.  There are two different reasons why we might use importance sampling, for this task.
First situation: If you don't have a way to sample from $p_z(z)$, but you do have a way to compute $p_z(z)$, then all of the above discussion still applies, and we can use importance sampling in this generalized setting.  In particular, we use the equality
$$\mathbb{E}_{z \sim p_z(z)}[f(z)] = \mathbb{E}_{z \sim q(z)}\left[{f(z) p_z(x) \over q(z)}\right],$$
and we use standard methods to estimate the right-hand side by drawing several samples from $q(z)$.  So, in this setting, the reason we use importance sampling is because there is no other choice: we can't use simpler methods, so we're forced to use this more sophisticated method.
Second situation: If we do have a way to sample from $p_z(z)$, then we don't have to use importance sampling, but it might still be to our benefit to do so.  In particular, your picture gives exactly the sort of situation that can occur, but you've drawn the wrong conclusion, because your intuition has led you astray.
To help you improve your intuition, I suggest drawing the same picture, but now imagine that the height of the peak of $f(x)$ is $1000\times$ higher than the peak of $p_z(z)$.  Then it is hopefully clear that sampling from $p_z(z)$ is sub-optimal: most samples will be from the center of $p_z(z)$, where $f(z)$ is close to zero.  However, the expectation will be dominated by the area in the tail where $f(z)$ is large.  Those samples will occur rarely if you sample from $p_z(z)$, but their value will be so huge that they will dominate.  The result is that naive sampling is inefficient: you need a lot of samples to make sure you obtain a few that are in the tail.  The way that this shows up is that the variance of the standard estimator is very high, and  the estimator will be unbiased in theory but in practice if you don't have a very large sample size, the estimator will often give values that are very wrong.
Importance sampling offers a better method.  Suppose we can find a distribution $q(z)$ that is approximately proportional to $p_z(z) f(z)$, and suppose we can sample from $q(z)$.  Then it turns out that using importance sampling with $q(z)$ yields a better estimator than standard sampling from $p_z(z)$.  In particular, the variance of the importance sampling estimator will be lower (its estimates will tend to be more accurate).  Formally, the optimal (most efficient) estimator sets $q(z)$ to be exactly proportional to $p_z(z) f(z)$, and any distribution $q(z)$ that is close to that will be close to optimal.
Hopefully, it is intuitive why this might be so.  If the peak of $f(z)$ is $1000\times$ higher than you drew it here, it's best to bias your sampling towards the area where $f(z)$ is large, and then you want to correct for that bias by dividing by some appropriate constant.  That's exactly what importance sampling does, if you use a distribution $q(z)$ that is proportional to $p_z(z) f(z)$.
At this point, you might be wondering, why not simply define $q^*(z) = p_z(z) f(z)$, and then sample from $q^*(z)$?  Well, two reasons.  First, this is not a distribution; we need to renormalize it so it sums to one.  So, the correct definition is $q^*(z) = p_z(z) f(z) / \int_t p_z(t) f(t) \; dt$.  This brings us to the second reason: we might not have any efficient way to sample from the resulting $q^*(z)$.  For starters, we might not have any efficient way to compute $\int_t p_z(t) f(t) \; dt$, and in addition, just because you can compute $q^*(z)$ for any $z$ of your choice is not enough to let you sample from such a distribution of your choice.  Importance sampling provides a solution to all of these challenges.  It doesn't require us to be able to compute the optimal distribution $q^*(z)$ or to be able to sample from it.  It lets us use any convenient distribution that is close to $q^*(z)$.
Comment: Thanks so much! The idea of visualizing a peak of $f(x)$, where the peak is $1000$ times higher was very helpful.
Comment: I do not see why the height of $f$ relative to the height of $p_z$ matters: the problem is invariant to the scale of $f$ in the sense that $\mathbb E[a\times f(Z)]=a\times \mathbb E[f(Z)]$ and that the optimal solution for $f$ is the same as the optimal solution for $a\times f(\cdot)$.
Comment: @Xi'an, For me at least, the proper intuition is easier to access when the height of $f$ is large, and it's easier to see why the reasoning in the post ("...which seems good since indeed...") is faulty.  It's intended as an intuition pump, not a formal piece of math.  (In terms of the mathematics, I suspect this is because the mean squared error of the naive estimator scales with $a^2$, so when $a$ is large, it is easier to see why the naive estimator is "imprecise", i.e., has a large variance.  However, I haven't checked the math on that carefully, so this might be bogus.)
Comment: At least, I think that's right.  Please feel free to enlighten me or correct me if there are errors in this answer!  I am not an expert in statistics, so I might well have fundamental misconceptions or misunderstandings.
Comment: @D.W. : you are correct about the variance being multiplied by $a^2$, but this is the case for all importance sampling proposals. Hence their relative order/comparison does not depend on the scale ($a$) of $f$.
Comment: @Xi'an, I know, but this is an intuition pump, not a formal mathematical proof of anything.  In a visualization multiplying by 1000 can sometimes help.  Formally, the original poster had an incorrect statement in their post, and I'm trying to help them with a visual example that makes it obvious it is incorrect.  Perhaps you don't need this intuition pump because your intuition is already correct; or perhaps this way of seeing it helps some people but not others; in any case, it helped me, and I am suspecting it'll help the original poster too.  Or perhaps I am misunderstanding something!
Answer: Let me give you a very simple example. Assume that $p$ is a standard Gaussian and that $f : x \mapsto 10^{8} \cdot \mathbf{1}_{x \geq 5}$. Then the expectation you're trying to compute is $10^8 \cdot \mathbb{P}(X \geq 5) \approx 28.7$. The intuition that the expectation will be $0$ because $f$ is 0 in the important regions of $p$ is wrong. If $f$ has extremely large values in regions of small mass under $p$ then you may have an expectation that is far from $0$.
With this in mind, of course if you use standard Monte Carlo to approximate this expectation, your estimates will be 0 almost all the time even if you use $100000$ samples to compute each MC estimate. This is quite far from $28.7$.
Meanwhile, if you do importance sampling with proposal $\mathcal{N}(5, 1)$ you get much much better estimates, as I illustrate through the following snippet. I estimate the root mean square error of such estimates by computing n_rep estimates.
from torch.distributions import Normal
from scipy.stats import norm

n_samples = 5000
n_rep = 1000
f = lambda x : 10.**8 * (x >= 5)
p = Normal(0., 1.)
q = Normal(5., 1.)

p_samples = p.sample((n_rep, n_samples))
q_samples = p_samples + 5

#Monte Carlo estimates, sampling from p
mc = f(p_samples).mean(-1)

#Importance Sampling estimates, sampling from q
log_weights = p.log_prob(q_samples) - q.log_prob(q_samples) #importance weights
IS = (f(q_samples) * log_weights.exp()).mean(-1)

print(f'Expectation value: {10**8 * (1 - norm.cdf(5))}')
print(f'RMSE Monte Carlo estimates: {mc.std()}')
print(f'RMSE IS estimates: {IS.std()}')

The code returns
Expectation value: 28.66515719235352
RMSE Monte Carlo estimates: 632.4555053710938
RMSE IS estimates: 0.9297240972518921

In short, importance sampling is very useful when you don't know how to sample from the distribution $p$ but it is also as much useful when you want to estimate "rare events" as is the case here.

Why do we need importance sampling?


Como usar o GestureDetector?

Question: Gostaria de um exemplo prático para esse método, pois quero que detete movimento para esquerda executa um comando e se for para direita executa outro comando.
Buscando na net encontrei este código parece estar funcionado, porém ele não deteta movimento por ter vários botões se alguém souber como corrigir esse problema. Link onde encontrei o código
public class MinhaActivity extends Activity implements OnGestureListener {

    private GestureDetector detector = null;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        this.detector = new GestureDetector(this);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(this.detector.onTouchEvent(event)) {
             return true;
        }
         return super.onTouchEvent(event);
    }

    @Override
    public boolean onDown(MotionEvent arg0) {
         return false;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

        if (Math.abs(e1.getY() - e2.getY()) > 250) {
            return false;
        }
        // Movimento da direita para esquerda
        if(e1.getX() - e2.getX() > 100 && Math.abs(velocityX) > 200) {
            //Faz algo aqui....
        } else if (e2.getX() - e1.getX() > 100 && Math.abs(velocityX) > 200) {
            //Faz algo aqui....
        }

    return true;
    }

    @Override
    public void onLongPress(MotionEvent event) { }

    @Override
    public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2, float arg3) {
         return false;
    }

    @Override
    public void onShowPress(MotionEvent arg0) { }

    @Override
    public boolean onSingleTapUp(MotionEvent arg0) {
         return false;
    }

}

Answer: Para conseguir detectar o movimento de swipe por cima dos botões ou de qualquer outra view, sem que ter que implementar essa lógica em cada uma das views, temos de encontrar um modo de interceptar esse movimento antes delas.
A classe ViewGroup tem o método onInterceptTouchEvent() que, quando implementado, permite interceptar os MotionEvent que são enviados às views filhas.
Se o método retornar true, o MotionEvent será passado ao método onTouchEvent() da ViewGroup, caso contrario, é passado ao onTouchEvent() da view onde ocorreu o evento.
Teremos então de escrever uma classe que herde de um ViewGroup(no caso FrameLayout) e implemente os métodos onInterceptTouchEvent() e onTouchEvent() de forma a tratar o movimento de Swipe.
public class SwipeInterceptor extends FrameLayout {

    public interface OnSwipeListener{
        public void onSwipeLeft();
        public void onSwipeRight();
    }

    private OnSwipeListener mSwipeListener;
    private int mTouchSlop;
    private boolean mIsDragged;
    private float mLastX;
    private float mLastY;
    private float mStartX;
    private float mDeltaXTotal = 0;

    public SwipeInterceptor(Context context, AttributeSet attrs) {
        super(context, attrs);
        setTouchSlop(context);
    }

    //Api level 21 ou superior
/*  public SwipeInterceptor(Context context, AttributeSet attrs,
            int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        setTouchSlop(context);
    }*/

    public SwipeInterceptor(Context context, AttributeSet attrs,
            int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setTouchSlop(context);
    }

    public SwipeInterceptor(Context context) {
        super(context);
        setTouchSlop(context);
    }

    public void setOnSwipeListenner(OnSwipeListener listener) {
        mSwipeListener = listener;
    }
    private void setTouchSlop(Context context){
        ViewConfiguration vc = ViewConfiguration.get(context);
        mTouchSlop = vc.getScaledTouchSlop();
    }
    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mLastX = event.getX();
                mLastY = event.getY();
                mStartX = mLastX;
                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                mIsDragged = false;
                break;
            case MotionEvent.ACTION_MOVE:
                float x = event.getX();
                float y = event.getY();
                float xDelta = Math.abs(x - mLastX);
                float yDelta = Math.abs(y - mLastY);

                float xDeltaTotal = x - mStartX;
                if (xDelta > yDelta && Math.abs(xDeltaTotal) > mTouchSlop) {
                    mIsDragged = true;
                    mStartX = x;
                    return true;
                }
                break;
        }

        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                if (mIsDragged && mSwipeListener != null) {
                    if(mDeltaXTotal > 0)
                        mSwipeListener.onSwipeRight();
                    else mSwipeListener.onSwipeLeft();
                }
                mIsDragged = false;
                mDeltaXTotal = 0;
                break;
            case MotionEvent.ACTION_MOVE:
                float x = event.getX();
                float y = event.getY();

                float xDelta = Math.abs(x - mLastX);
                float yDelta = Math.abs(y - mLastY);

                 mDeltaXTotal = x - mStartX;
                if (!mIsDragged && xDelta > yDelta && Math.abs(mDeltaXTotal) > mTouchSlop) {
                    mIsDragged = true;
                    mStartX = x;
                    mDeltaXTotal = 0;
                }
                mLastX = x;
                mLastY = y;
                break;
        }

        return true;
    }
}

Como se pode verificar o método onInterceptTouchEvent() só retorna true no caso de MotionEvent.ACTION_MOVE, pois é apenas esse o movimento que queremos interceptar.
Todo o código se resume a alguma matemática para saber se o movimento feito deve ser considerado como um Swipe e qual a sua direcção.
A classe declara a interface OnSwipeListener com os métodos onSwipeLeft() e onSwipeRight() que serão chamados quando esses movimentos forem detectados.
A classe que os implementar deve ser registrada através do método setOnSwipeListenner().
Implementação
A implementação passa por, primeiro colocar o seu layout dentro do nosso FrameLayout
<nome_da_sua_package.SwipeInterceptor xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/swipe">

</nome_da_sua_package.SwipeInterceptor>

e depois, implementar a interface OnSwipeListener.
Uma das formas possíveis é fazer a sua Activity implementá-la:
public class MainActivity extends Activity implements OnSwipeListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Obtém a referência ao SwipeInterceptor.
        SwipeInterceptor swipe = (SwipeInterceptor)findViewById(R.id.swipe);
        //Registra a nossa Activity para receber os eventos onSwipeLeft e onSwipeRight
        swipe.setOnSwipeListenner(this);
    }

    // Declaração dos métodos da interface OnSwipeListener
    @Override
    public void onSwipeLeft() {

        Toast.makeText(MainActivity.this, "Swipe Left", Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onSwipeRight() {

        Toast.makeText(MainActivity.this, "Swipe Right", Toast.LENGTH_SHORT).show();
    }

}

Fonte de inspiração: Documentação do Android e este artigo.
Comment: tenho uma pergunta este método é para qual versão do `Android `
Comment: Julgo que funciona em qualquer versão.
Comment: to achando que funciona no API 11 e superior, precisava testar nesse API, to usando genymotion mas tem esse API.
Comment: Não entendi a sua dúvida.
Comment: é que eu precisava dessa versão do android para testar, to usando genymotion que um ótimo emulador para testar as aplicação, então eu fiz uma pergunta a respeito mas ninguém respondeu ainda http://pt.stackoverflow.com/questions/69598/como-instalar-api-11-do-android-no-genymotion
Comment: Se o *genymotion* não tem essa versão não há nada a fazer.
Comment: a respeito da sua resposta como usar para ficar trocando de layout exemplo tenho 3 layout ao fazer o movimento para direita ele vai trocando de layout, hora que acabar ele repete assim o mesmo para esquerda
Comment: O melhor é usar um [ViewPager](http://developer.android.com/intl/pt-br/training/animation/screen-slide.html)
Answer: Tente isso (refactory):
adicione o atributo:
private GestureDetector gesto;

depois no onCreate use esse código:
CustomGestureDetector customGestureDetector = new CustomGestureDetector()
gesto = new GestureDetector(this, customGestureDetector);
View v = new RelativeLayout(this);
v.setOnTouchListener(new OnTouchListener() {
   @Override
   public boolean onTouch(View v, final MotionEvent event) {
      gesto.onTouchEvent(event);
      return true;
   }
});

Vamos tentar usando método.
Adicione esse método:
@Override
public boolean onTouchEvent(MotionEvent event) {
    gesto.onTouchEvent(event);

    return super.onTouchEvent(event);
}

e esse:
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        if (e1.getX() < e2.getX()) {
           Log.d(TAG, "Left to Right swipe performed");
        }

        if (e1.getX() > e2.getX()) {
           Log.d(TAG, "Right to Left swipe performed");
        }

        if (e1.getY() < e2.getY()) {
           Log.d(TAG, "Up to Down swipe performed");
        }

        if (e1.getY() > e2.getY()) {
           Log.d(TAG, "Down to Up swipe performed");
        }

        return true;
 }

Comment: `v.setOnGestureListener(new OnGestureListener(){` esta apresentado erro nessa linha será que não esta faltando nada no código?
Comment: Fiz uma edição no código. da uma olhada se agora funfa.
Comment: ainda não, esta apresentando problema `customGestureDetector` erro -->`customGestureDetector cannot be resolved to a variable` e aqui `public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) ` erro -->`The method onFling(MotionEvent, MotionEvent, float, float) of type CalculadoraActivity must override or implement a supertype method`
Comment: Desculpe fera faltou essa parte: CustomGestureDetector customGestureDetector = new CustomGestureDetector(); já editei o código da outra olhada.
Comment: Ainda não esta funcionando, mas mesmo assim valeu
Answer: Boa noite, bom amigo! Dá uma olhadinha se isso funciona para você:
GestureListener.java
class GestureListener extends GestureDetector.SimpleOnGestureListener
{

       static String currentGestureDetected;

      @Override
      public boolean onSingleTapUp(MotionEvent ev) {
          currentGestureDetected=ev.toString();

        return true;
      }
      @Override
      public void onShowPress(MotionEvent ev) {
          currentGestureDetected=ev.toString();

      }
      @Override
      public void onLongPress(MotionEvent ev) {
          currentGestureDetected=ev.toString();

      }
      @Override
      public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
          currentGestureDetected=e1.toString()+ "  "+e2.toString();

        return true;

}
  @Override
  public boolean onDown(MotionEvent ev) {
      currentGestureDetected=ev.toString();

    return true;
  }
  @Override
  public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
      currentGestureDetected=e1.toString()+ "  "+e2.toString();
    return true;
  }
}

MainActivity.java
public class MainActivity extends Activity
{

    private GestureDetector mGestureDetector;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // vincula o gestureDetector ao GestureListener
        mGestureDetector = new GestureDetector(this, new GestureListener());
    }

    //sempre que você tocar na tela o método onTouch() é chamado
    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        //o método onTouchEvent analisa que tipo de toque foi (arrastando, etc)
        boolean eventConsumed=mGestureDetector.onTouchEvent(event);
        if (eventConsumed)
        {
            Toast.makeText(this,GestureListener.currentGestureDetected,Toast.LENGTH_LONG).show();
            return true;
        }
        else
            return false;
    }
}

A fonte deste código pode ser encontrada aqui. Se ainda tiver dúvidas ou não conseguir fazer funcionar, por favor me avise!
Comment: tenho uma leve impressão de ter tentado, bom mais vou tentar novamente esse código assim que eu arrumar o eclipse, mais vale salientar que gostaria de saber como fazer o GestureDetector funcionar em cima dos botões.

Como usar o GestureDetector?


How come it says array is undefined?

Question: Here is a javascript sample:
var obj =
{
   options:  [],

   init:  function( )
   {
       options['one'] = 'one';
       for( k in options )
       {
          alert( options[k] );
       }
   }
};

instead of prompting "one", it says undefined, why?
Comment: be careful when using a 'for x in obj' loop, if you run that code you will see a whole heap of interesting functions being alerted.
Answer: You would need to reference it as obj.options.
Aside from that, you should use an object {} instead of an array [] if you're not going to be using numeric indexes.
var obj =
{
   options:  {},

   init:  function( )
   {
       obj.options['one'] = 'one';
       for( k in obj.options )
       {
          alert( obj.options[k] );
       }
   }
};

If you call the init() function from the obj reference, then you could use this inside the init function instead of obj.
var obj =
{
   options:  {},

   init:  function( )
   {
       this.options['one'] = 'one';
       for( k in this.options )
       {
          alert( this.options[k] );
       }
   }
};

obj.init();  // Makes `this` refer to `obj` in the `init` function

As @CMS noted, you should declare your variables with var.  In your for loop, k is no declared with var, and as such will become a global variable.
Comment: Off-topic but in addition, I would recommend to use the `var` statement to declare the `k` variable on the `for-in` loop: `for(var k ...` otherwise `k` will become a property of the global object (`window.k`).
Comment: @dave: Using `this` would depend on how the `init` function is called. If you're doing `obj.init()`, then yes, you could use `this.options` inside the `init` function.
Comment: @david: Not always. See above.
Comment: +1 for more complete answer than mine, and the `[] => {}` that I missed. Deleting my answer shortly.
Comment: If you use it correctly, then 'this' is perfectly safe to use, and is far more adaptable because you're not hardcoding the name of the object into its implementation.
Comment: @david: I didn't say it wasn't safe. It just can't be assumed.
Comment: @patrick, but you're assuming the object will always be called obj, what if later he does something like `someArray.push(obj); obj=something else;`?
Comment: wow, these are all good learning tips, thanks a bunch.  I clearly need to go back and learn javascript objects again.
Comment: @david: We don't know the ultimate use of the code. I'm not making *any* assumptions. As I said above *"It just can't be assumed."* Along the same line, what if later he passes that function as a callback? `someOtherFunc( obj.init )` When `someOtherFunc` calls the callback it won't be called from the context of `obj` unless that function happened to have a reference to it and knew to use it. Or if it gets assigned to a variable? `var func = obj.init; func()` Again it is not called from the context of `obj`.
Comment: Woah, ease up, all I'm saying is that we are both making assumptions. I just find it more likely that the object will be renamed, and less likely that he will pass function pointers around.
Comment: @david: You may be absolutely right, especially with a name like `init`. Not enough info in the question to know for sure. I'd tend to lean toward `this` as well if for no other reason than the fact that it is a direct reference to the object without a scope chain traversal.
Answer: What you're doing looks very similar, in form and concept, to something called the 'Module pattern' in javascript.
It is a very powerful tool, and if you want to learn I highly recommend you read up on it.
Here is your code, rewritten as a module, with changes to avoid polluting the global scope, and to fix a potential problem with your for in loop.
It also defines options as an object, rather than an array, as you seem to be using it as a hashtable rather than with numeric indices.
var module = (function() {
    //here options is private
    var options = {};

    var init = function() {
        options['one'] = 'one';
        for (var k in options) {
            if(options.hasOwnProperty(k)){
                alert(options[k]);
            }
        }
    };

    //These are the things that are public
    return {
        init:init
    };
}());

module.init();

alert(module.options); //undefined (because it's private)

How come it says array is undefined?


The random error term is assumed to follow the normal distribution with a mean of 0 in linear regression at each point in x axis

Question: while going through http://reliawiki.org/index.php/Simple_Linear_Regression_Analysis

They have plotted a normal distribution at X=65 and X=90 and say that error term follow a normal distribution , since linear regression is a function that out puts only one value for a given X , how did they plot the distribution?
Answer: You seem to be confusing the sample with the population. There's a population of possible response-values at any given $x$ (hence the conditional distribution [$Y|x$]), but in your sample you might only observe a single $y$-value at that specific $x$. Or you might observe two values, or 200 values (in which case the ECDF of the sample y's at that x-value might then start to look something like the population cdf there)
Answer: For a linear regression you assume that the data come from a normal distribution, whose mean is a function of the predictor:
$$y \sim N(\mu=\beta_0 + \beta_1 x, \sigma)$$
After fitting (using maximum likelihood), you get estimates for the $\beta$s (typically indicated by adding the hat ^: $\hat{\beta}_1$) and for $\hat{\sigma}$. The figure plots the normal distribution using this estimated $\hat{\sigma}$, with the mean at the expected value for $\mu = \hat{\beta}_0 + \hat{\beta}_1 \cdot 65$ and 90, respectively.
It is more common (but less generalisable) to write this as $y_i = \hat{\beta}_0 + \hat{\beta}_1 x_i + \varepsilon_i$ (or its vector equivalent). In this case, we assume $\varepsilon$ to be normally distributed: $\varepsilon \sim N(0, \sigma)$, i.e. centred on the expected value for a given $x_i, E(y_i | x_i) = \hat{\beta}_0 + \hat{\beta}_1 x_i$.
That's what the text in the figure tries to say. Personally, I like to see the hat for estimated values (or move from Greek to Latin: $\hat{\beta} = b, \hat{\sigma}=s$); and I assume that the meaning of $\varepsilon$ is explained in the text. (I don't like the way $\varepsilon_{90}$ suggests that for $x=90$ $\varepsilon$ would always be one specific value; which of course it would not: that's why the author drew the distribution).


.ToString Error (vb.net)

Question: For some reason, this is not working for me , and I'm not sure. I'm trying to make a Set Home Page button for my webbrowser, and this is the code to check if a page is set, and then goto the page:
    Dim HomepageInfo As String
    If IO.File.Exists(Environment.SpecialFolder.ApplicationData & "\Homepage.Info") = True Then
        HomepageInfo = IO.File.ReadAllText(Environment.SpecialFolder.ApplicationData & "\Homepage.Info")
        WebBrowser1.Url = HomepageInfo.ToString
    Else
        'Create a File with a Default Homepage (www.google.com)
        IO.File.WriteAllText(Environment.SpecialFolder.ApplicationData & "\Homepage.Info", "www.google.com")
    End If

And this is showing as an error: HomepageInfo.ToString, and the error is: "Value of type 'String' cannot be converted to 'System.Uri'."
Thanks for any help!
Comment: How is `WebBrowser1` declared?
Answer: WebBrowser.Url property accepts an uri object not a string:

Property Value Type: System.Uri A Uri representing the URL of the
  current document.

So you have to use an instance of Uri class:

Provides an object representation of a uniform resource identifier
  (URI) and easy access to the parts of the URI.

Code:
Dim HomepageInfo As String
If IO.File.Exists(Environment.SpecialFolder.ApplicationData & "\Homepage.Info") = True Then
    HomepageInfo = IO.File.ReadAllText(Environment.SpecialFolder.ApplicationData & "\Homepage.Info")
    WebBrowser1.Url = New Uri(HomepageInfo.ToString)
Else
    'Create a File with a Default Homepage (www.google.com)
    IO.File.WriteAllText(Environment.SpecialFolder.ApplicationData & "\Homepage.Info", "www.google.com")
End If

Answer: Try have to use like this
WebBrowser1.Url = new Uri(HomepageInfo.ToString);

Answer: Quite simple: Your WebBrowser1.Url is not a string, but an URL - an URL is NOT a string, but behaves idfferently, e.g. options for checking he validity of an URL.
You can construct a new URL to circumvent this problem:
WebBrowser1.Url = new Uri(HomepageInfo.ToString)
But this might fail, of the given string is not a valid URL.

.ToString Error (vb.net)


How to Express the domain of the mult-valued function $\sqrt{1-z^{2}}$?

Question: In the analysis of the function $w(z)=\sqrt{1-z^{2}}$ I've set the branch cuts from $-\infty$ to $-1$ and from $1$ to $\infty$. I would like to know how can I express the domain of this function when the branch cut is set this way?
Answer: As a subset of $\mathbb C$ the domain is just what you described, i.e., $\mathbb C\setminus(-\infty, -1]\setminus[+1,+\infty).$
If you want a domain where the multivalued square root becomes single-valued, use two copies of $\mathbb C$ with the open half lines doubled and the points $\left\{-1,+1\right\}$ taken away, and identify the half line that is the boundary of the upper half plane from one copy with the half line that is the boundary of the lower half plane from the other copy.
As a set,
$$D=\mathbb C_1\setminus\left\{-1,+1\right\}_1\cup\mathbb C_2\setminus\left\{-1,+1\right\}_2$$
where the indices 1 and 2 are used to distinguish disjoint copies.
The function $f$ can be defined single-valuedly on $D$ and the values it takes on the two indexed versions of a complex number are each other's negatives.


regression equation of factorial design

Question: I was wondering why I get a different kind of regression equation when I do the same data in a different way(create DOE in the minitab vs type the data myself ).
For example, when I do the job as the picture below:

I can get the regression equation.
However, If I create a new factorial design as the picture below,
I got a different equation, and I did not know how to use that equation to predict the response.

I did the setting because I would like to analyze the 3 level experiment.
I would like to know what the second equation means.
Answer: You've omitted a stage from your first example. After reading the data from excel you must have used DOE -> Define Custom Factorial Design and specified that the data was "uncoded".

That caused'power' and 'time' to be treated as continuous variables which can take any real value. In terms of measurement level <Wikipedia> they are at least interval, if not ratio. That is to say, for exanmple, the difference between 50 and 100 is the same as that between 150 and 200. In Minitab's nomenclature <link> they are treated as continuous variables.  In the regression equation 'power' or 'time' indicate the actual values.
In the second example 'power' and 'time' are treated as factors, after all you did create a factorial design. They can take only the discrete values you indicated, not intermediate values. In terms of measurement level they are no more than ordinal, In Minitab's nomenclature they are categorical. The analysis treats the values as just 'Low' or 'High' with no regard to the values you entered, those values are just labels for the 'Low' and 'High' levels. In the regression equation <code>- 1.03000 power_50 + 1.03000 power_250</code> means: if power = 50 add -1.03 (i.e. subtract 1.03),  if power = 250 add 1.03. NOTE: power cannot take any other values.
Answer: Thanks,
However, I did not use the "Define Custom Factorial" to design the experiment.
I used the Create Factorial design--> general full factorial where I can set 3^k design in the future. I think in the general full factorial one, they did not treat the factor as continuous. Moreover, there is no option for me to choose "Uncoded" as you said.
Therefore, How do I create a 3^k design with factors treated as continuous one in general full factorial design, or is there other ways?
I would like to get the continuous regression equation with 3^k design.
Comment: 1) I'm not expert in Stack Exchange but think this is not the way to ask follow-up questions.
Comment: 2) You need more intensive help than I can give; consult a local expert.
3) Your words contradict Minitab's meanings. E.g. you say "factors treated as continuous" but Minitab says "Factors can be … based on a continuous variable but only use a few controlled values".
4) Design is not analysis. You can analyse a factorial design with regression.
5) For a 3-level design with continuous variables consider a face centred response surface design.

regression equation of factorial design


Proving increasing function, base < 1, exponent increasing

Question: For a fair lottery game where the odds of $1$ ticket winning are $1$ in $p$, where you can spend a total of $K$ dollars, and where you will spread your ticket purchases equally among $n$ draws, prove that the odds of winning at least once decrease as $n$ increases.
An online "discussion" I'm having about the relative merits (such as they are) of different strategies of playing the lottery. With a fixed amount of money to spend on lottery tickets, he claims that it's better to spread your ticket purchases out over multiple draws, while I say it's better to spend all the money on unique tickets for one draw.
I can show that I'm correct using absolute numbers, but I'm trying to prove a general case.
$$p \ge K \ge n \ge 1$$
The odds of losing every time (never winning) are given by:
$${\left(p-\frac K n\over p\right)}^n$$
I can throw "actual" numbers in there for p, K, and n and show that playing \$100 all at once is better than playing \$10 ten times or \$1 one hundred times.
I want to show the general case. That is, I want to show that for any given p and K, the odds of losing every time:
$${\left(p-\frac K n\over p\right)}^n$$
increase as n increases from 1 to K. I started with the presumption:
$${\left(p-\frac K {n+1}\right)^{n+1} \over {p^{n+1}}} > { \left(p-\frac K {n}\right)^{n} \over {p^n}}$$
but college math was a long time ago, and I'm stuck at this point (I've probably gone off in the wrong direction):
$${\left(p-\frac K {n+1}\right)^{n+1} \over \left(p-\frac K {n}\right)^{n}} > p$$
Any pointers on how I can "simplify" that expression or otherwise continue with a proof?
Answer: When you say it is better to play all your money in one draw, that is correct if by better you mean a better chance of winning something.  Each ticket has the same expected value.  The improvement from playing the same draw comes from the fact that you cannot win more than once.  Let's contrast throwing a die.  Playing one number on two separate rolls gives you $\frac {11}{36}$ chance of winning at all, $\frac {10}{36}$ that you win once and $\frac 1{36}$ that you win twice.  The total winnings are $\frac {12}{36}=\frac 26=\frac 13$.  If you play two numbers on one roll, you can only win once, but your chance of winning is $\frac 26=\frac 13$  Yes, you have a higher chance of winning once, but the same total winnings.  The other side of the "discussion" may be focusing on expected value instead of the chance of total loss.
What you are trying to prove is that $(1-\frac an)^n$ is monotonically increasing with $n$ (where $a=\frac Kp$)  It starts at $1-a$ and approaches a limit of $\exp(-a)$ as $n \to \infty$  If you expand the binomial, it starts $1-a+\frac {n(n-1)}{2n^2}a^2-\dots$  When $a \lt 1$ the terms are decreasing and the second order term increases with $n$
Comment: What I mean by "better" is that you have a greater chance of winning the jackpot (matching all numbers) if you play all your money in one draw.
Comment: I'm not sure the 12/36 value above is correct. When throwing a die, playing one number on two separate rolls gives a 1/36 chance of winning both times, 10/36 chance of winning exactly once, and 25/36 chance that you lose both times. The total chances of winning at least once are 11/36, not 12/36. Playing two numbers on one roll gives a 2/6 (1/3) chance of winning (exactly once), which is "better" than 11/36.   (Unless I've completely misunderstood the comment)
Comment: Ah - and the "other side of the 'discussion'" is focused exclusively on winning the jackpot at least one time. It's presumed that the value of the jackpot is a few orders of magnitude greater than K, and that winning twice has no greater value than winning once (in fact, one presumption is that once you've won once, you'll stop playing).
Comment: @user159407:  On the die roll, I said the chance of winning at least once betting on two rolls was $\frac {11}{36}$  The mathematics is not hard and you seem to understand it clearly.  Those arguing one way of playing is "better" than another should define "better" carefully.  You have done so-by saying the chance of winning at least once.  Having done so there is a clear answer and it is to play all your funds on on draw.  If the chance of more than one win is very small, the difference between playing one draw or more will be very small.


Find the number of $f: A \to B$ where there is no element in $B$ with $3$ sources

Question:
Let $A$ and $B$ be sets such that $|A| = 8$ and $|B| = 5$. Find the number of functions $f: A \rightarrow B$ such that there is no element in b that has 3 sources (that means, for all $b \in B \rightarrow |\{ a \in A | f(a) = b \} | \neq 3$

This is a question of Graph-Theory from one of my previous exams, but I have absolutely no clue on how to solve it, however, it might have something to do with the Erdos-Szekeres rule (for all two integers $s$ and $t$ : $R(s,t) \leq {s+t-2 \choose s-1 } $
Answer: The total number of functions $A \to B$ is $5^8$.
For each $b \in B$, the number with $|f^{-1}(b)| = 3$ is ${8 \choose 3} 4^5$.
For every $b_1 \ne b_2 \in B$, the number with $|f^{-1}(b_1)| = 3$ and $|f^{-1}(b_2)| = 3$ is ${8 \choose 3} {5 \choose 3} 3^2$.  There are none with
$|f^{-1}(b)|=3$ for three
 different $b$.  Now use the inclusion-exclusion principle.
Comment: This answer is a trivial Enumeration one. (and I have thought of it).
But, is there a way to solve it using graph-theory? (especially the Erdos-Szekeres rule)


Differential geometry parallel transport

Question:
Let $\alpha \colon I \to \mathbb{R}^{n+1}$ be a parametrized curve with $\alpha(t) \in S_1 \cap S_2$ for all $t \in I$, where $S_1$ and $S_2$ are two $n$-surfaces in $\mathbb{R}^{n+1}$.
  Suppose that $\mathbf{X}$ is a vector field along $\alpha$ which is tangent to both $S_1$ and to $S_2$ along $\alpha$.
(a) Show by example that $\mathbf{X}$ may be parallel along $\alpha$ viewed as a curve in $S_1$ but not parallel along $\alpha$ as a curive in $S_2$.
(Original image here.)

I stuck in above question. I have some idea but don't know how to proceed.
Idea: Consider a sphere of unit radius as one surface and remove one point from $X - (0,0,-1/2)$ and this acts as the other surface. Now define a path as $(0.75 \cos t,0.75 \sin t, -1/2)$ and then define a vector field as $\mathbf{X} = (0.75 \cos t, 0.75 \sin t, 0)$. These satisfy all conditions but I cannot reach the final result.
Any other example is also welcome but with more of geometric intution.
Answer: Take a sphere and intersect it with a plane going through the origin. The intersection is a geodesic of the sphere, so there is a nice candidate for the vector field. Once you figure out the vector field, it should be easy to show that it is not parallel when you view it on the plane.
Comment: can you explain it a bit more? We define a vector field on great sphere then how it is tangent to both sphere and plane? Why is it not parallel viewing from the plane?
Comment: We define a vector field *along the curve* which is both tangent to the plane and to the sphere. What vector field is parallel to a geodesic? This is the candidate. Now, you know that parallel vector fields on a plane inside $\mathbb{R}^n$ with the standard metric must be constant. Use those informations together.
Comment: Why tangent vectors to great circle form  parallel field? What is explicit vector field X (I want some example)?


Reset offset variable in API when using a for loop

Question: I am working with a real estate API pulling rental listings. I'd like to loop through a list of zipcodes to pull the data. The API requires an offset of 500 rows of data or less. The code below works fine until the while loop hits the second zipcode. The issue is that after the first zipcode has run successfully, I need the offset variable to reset to 500 and begin counting up again until the while loop breaks for the second zipcode in the list.
<code>`# This just formats your token for the requests library.
headers = {
"X-RapidAPI-Key": "your-key-here",
"X-RapidAPI-Host": "realty-mole-property-api.p.rapidapi.com"
}

# Initial Limit and Offset values.
limit = 500
offset = 0
zipCode = [77449, 77008]

# This will be an array of all the listing records.

texas_listings = []

# We loop until we get no results.
for i in zipCode:
while True:
    print("----")
    url = f"https://realty-mole-property-api.p.rapidapi.com/rentalListings?offset=.     {offset}&limit={limit}&zipCode={i}"
    print("Requesting", url)
    response = requests.get(url, headers=headers)
    data = response.json()
    print(data)
    # Did we find any listings?
    if len(data) == 0:
    # If not, exit the loop
        break

# If we did find listings, add them to the data
# and then move onto the next offset.
    texas_listings.extend(data)

    offset = offset + 500
</code>
`
Here is a snippet of the final printed output. As you can see, zipcode 77008 gets successfully passed to the zipCode variable after the 77449 zipcode returns an empty list and breaks the loop at offset 5500. However, you can also see that the 77008 offset starts at 5500 and it appears there aren't that many listings in that zipcode. How do I reset offset variable to 500 and begin counting again?
Answer: You can reset the offset variable back to 500 before starting the next iteration of the loop over the next zip code.
<code>for i in zipCode:
while True:
    print("----")
    url = f"https://realty-mole-property-api.p.rapidapi.com/rentalListings?offset={offset}&limit={limit}&zipCode={i}"
    print("Requesting", url)
    response = requests.get(url, headers=headers)
    data = response.json()
    print(data)
    if len(data) == 0:
        break
    texas_listings.extend(data)
    offset = offset + 500
offset = 500 # reset offset to 500 for the next zip code
</code>
Comment: Thank you, this works just as my answer above does.
Answer: Update: put the offset and limit within the for loop and it works the way I expect.
<code># We loop until we get no results.
for i in zipCode:
limit = 500
offset = 0

while True:
    print("----")
    url = f"https://realty-mole-property-api.p.rapidapi.com/rentalListings?offset={offset}&limit={limit}&zipCode={i}"
    print("Requesting", url)
    response = requests.get(url, headers=headers)
    data = response.json()
    print(data)
    # Did we find any listings?
    if len(data) == 0:
    # If not, exit the loop
        break

# If we did find listings, add them to the data
# and then move onto the next offset.
    texas_listings.extend(data)

    offset = offset + 500

texas = pd.DataFrame(texas_listings).append(texas,
ignore_index=True)
texas['date_pulled'] = pd.Timestamp.now().normalize()
</code>


How to present html tags in radio label text with woocommerce_form_field()?

Question: I use following array and need to assign a css class selector to the first value of array, but output displays HTML markup too!
woocommerce_form_field(
    $field_id,
    array(
        'type'          => 'radio',
        'class'         => array('form-row-wide'),
        'options'       => array(
            'alert' => '
Please allow 2-5 business days for delivery after order processing.
 ',
            jdate(('d F Y'), $twoDaysAfterTomorrow ) => jdate((' l ، j F Y  '), $twoDaysAfterTomorrow ),
        )
    )
);

However this is showing unrendered radio label text like:

Please allow 2-5 business days for delivery after order processing.

How is it possible to use HTML tags within field label text and have the markup rendered on the webpage?
Comment: Why are you needlessly wrapping the first argument of `jdate()` in parentheses?
Comment: @mickmackusa it is pre-defined function : `jdate( $format , $timestamp , $none , $time_zone , $tr_num );` and I use it to convert date to a native form.
Comment: `'d F Y'` is sensible.  `('d F Y')` is needless code bloat.
Comment: @mickmackusa Yup but does it help to omit  from code output?
Answer: You are fighting again the native behavior of the code.
See https://woocommerce.github.io/code-reference/files/woocommerce-includes-wc-template-functions.html#source-view.2668
esc_html( $option_text );

This means that no matter what string you pass into that radio markup building function, the label's text will be html encode to keep your site safe.
If you need to find a solution, then perhaps you could try to override/overwrite that function (not recommended), or write a new function that delivers the desired output without html encoding the text, or just manually create the desired output if this is a solitary use case.
I do not use WP, so I will not be providing a ready-made solution.  I suspect that you will be able to engineer your own solution based on the linked source code.
Answer: Use \" for inner quotes. https://3v4l.org/DkHT1
Comment: It does not work. Still output of code is similar to source and I see this line as output : Please allow 2-5 business days for delivery after order processing.
Comment: You use an arrow for a named array, after the first comma, you already have a regular array, not named. options => array(key=>value, wtf=>value, VALUE)


Custom Vibe sequence in Pebble.js?

Question: I have developed a Watchapp with Pebble.js that fetches a remote file, containing an integer, and emits that many "short" Vibe events.
The trouble is: Vibe events do not happen if one is currently in process. I have resorted to something like this to try to spread them out (where BUMP_COUNT_INT == number of Vibes to emit):
    for (var i = 0; i < BUMP_COUNT_INT; i++) {
      setTimeout(function(){
        Vibe.vibrate('short');
    }, 900*i);

However, even the 900ms( * Vibes) isn't consistent. There is sometimes more or less space between them, and they sometimes merge (causing fewer Vibes than expected).
It appears that the C SDK is capable of custom sequences.
I was hoping someone had come across a cleaner workaround, or a more stable way to pull this off using Pebble.js ... ?
Should I just accept that I'll have to spread the Vibes out even further, if I want to continue with Pebble.js?
What would you do?
Answer: Custom patterns are not available in Pebble.js but you could easily add a new 'type' of vibe in Pebble.js and implement it as a custom pattern in the C side of Pebble.js.
The steps would be:

Clone the Pebble.js project on GitHub and get a local copy. You will need to download and install the Pebble SDK to compile it locally on your computer (this will not work on CloudPebble).
Declare a new type of vibe command in src/js/ui/simply-pebble.js (the Pebble.js JavaScript library):
var vibeTypes = [
  'short',
  'long',
  'double',
  'custom'
];

var VibeType = makeArrayType(vibeTypes);

Create a new type of Vibe in src/simply/simply_msg.c
enum VibeType {
  VibeShort = 0,
  VibeLong = 1,
  VibeDouble = 2,
  VibeCustom = 3,
};

And then extend the Vibe command handler to support this new type of vibe in src/simply/simply_msg.c
static void handle_vibe_packet(Simply *simply, Packet *data) {
  VibePacket *packet = (VibePacket*) data;
  switch (packet->type) {
    case VibeShort: vibes_short_pulse(); break;
    case VibeLong: vibes_break_pulse(); break;
    case VibeDouble: vibes_double_pulse(); break;
    case VibeCustom:
      static const uint32_t const segments[] = { 200, 100, 400 };
      VibePattern pat = {
        .durations = segments,
        .num_segments = ARRAY_LENGTH(segments),
      };
      vibes_enqueue_custom_pattern(pat);
      break;
  }
}

An even better solution would be to suggest a patch so that any custom pattern could be designed on the JavaScript side and sent to the watch.
Comment: GREAT idea, and thanks for the insight into the C library. I was avoiding it, but it looks like I'll have to dig in either way. THANKS!

Custom Vibe sequence in Pebble.js?


Why one shouldn't play the 6th string of an A chord on guitar?

Question: Well everything is in the title: Why one shouldn't play the 6th string of an A chord on guitar?

As you may see on the diagram above we are supposed to strum the 1st string. But the 1st one is the same as the 6th one. So this is why I don't understand why we don't strum the 6th string on the A chord.
Thanks
Answer: You can play it; you'll be playing the a second inversion of the A major chord, with the fifth (E) in the bass.
However,

The bass notes of the guitar are quite low, so playing two notes a fourth apart can sound rather muddy. (See this recent question, among others)
In many cases, an 'A' notated as the chord is intended to also indicate that A is the bass note. If that's the case, you might want to avoid the low E string, and ensure that the lowest note is A (especially if playing the piece solo, without a bassist) to get the correct movement of the 'bassline' from one chord to the next.
Comment: @BruceWayne I probably go for a combination of Neil and Todd's techniques : aiming accurately, but also muting where necessary. Even with accurate strumming, a string might start vibrating due to energy it picks up  from the air or the instrument body.
Comment: @BruceWayne Oh I mute the heck out of the 6th string, so that I don't have to be as accurate as Neil suggests. It's probably worth noting that I play with a thumb over the top grip, which means I can mute the 5th and 6th strings with my thumb, which makes muting them much more practical than with other grips.
Comment: Just curious - do most people actually mute that 6th string? Or is that usually just noted for tabs, but in practice, people leave it open?
Comment: You learn to strum accurately so as to be able to strum 6, 5 or 4 strings.
Answer: As topo says, you can. In fact, sometimes, you have to. If you are playing a bar of A, and the accompaniment is open A, A chord, open E, A chord, it's what you do. Yes, often, the chord sounds better without the V underneath, but if you're strumming along to something, and yoe happen to hit tha E as well, it won't be wrong. A lot of the chord windows try to show chords in root position, as this is.Open C is another, yet with a G on bottom string, it's not bad at all. Same goes for all the barre chords that use the A shape - Bb on fret 1, B on fret 2, etc.
Answer: Even when strumming a chord, the notes aren't played simultaneously.  There will be a time when only one string is sounding.  Consequently, since the first string which is plucked will be more noticeable than all the others, one should try to make that be the note one wants to be most noticeable.  The two most important notes in the A major chord are usually the A and the C#.  The A is what establishes the chord as some kind of A chord, and the C# establishes it as a major chord.  Further, if the chord is being used as the dominant for the key of D, the C# serves as the leading tone for the key, making it a very important note.  Consequently, when playing an A chord one might want to emphasize the A or the C#, but would less often want to emphasize the E.
If one were playing a guitar with the lower strings reversed (as I usually do), then the most prominent note of A-E-e-a-c#'-e' would would be initial A even though it's not the lowest note.  When plucking rather than strumming I usually avoid the low E, but it's pretty harmless so long as it's not the first note played.  When strumming a standard-tuned guitar, however, the only way to strum an A chord without the low E being the first note is to omit that note altogether.
BTW, in some styles of bass-strum accompaniment it may be useful to have the bass line go between two notes of each chord; one should generally be the root of the chord, and the other should often be an "important" note in the key, such as the tonic, dominant (fifth), or leading tone (major seventh).  In the key of A or E, it may be good to have an A chord that includes the low E following an A chord without it; that's less likely to work well in in D major, though.
Comment: The time between striking strings when strumming with good technique is so short that human hearing considers them all to be struck at the same time. The choice of lowest sounding note has a much greater psychoacoustic and musical impact than simple note order. What might be making you think the first plucked string is important is that you might be playing it more loudly than the others, which is quite common.
Comment: Looks like a casual strumming rate for me creates less than 7ms delay between strings. The Haas effect for complex sounds occurs with delays as long as 40 ms, and even with clicks (which are more easily distinguished) it can be as long as 5 ms, so it's reasonable to conclude a Haas delay as being between 5 and 40 ms for guitar, and likely it's greater than 7 ms. Forgetting all of that for a moment, not muting the open low E string when playing an A major chord sounds just as bad *whether one plays upstrokes or downstrokes*, so order of striking strings is not important.
Comment: @ToddWilcox: Have you actually tested how things sound with a guitar strung as I have described?  i have.  A not terribly good recording I made some time ago can be found at https://www.youtube.com/watch?v=aRwT3E9iRfA (listen for the Bm and A chords).  The low F# and E are audible within those chords, but the Bm and A are more prominent than they would be in standard tuning (sorry I don't have a recording using the same amp with a standard-tuned guitar for reference).
Comment: I wasn't trying to say it doesn't sound different. Only that the timing of striking the strings is not part of the difference. One merely has to take sample of each string and play them back in different orders with spacing of about 1ms to hear that.
Comment: I would be interested in learning more about the reason for reversing the E and A string.  Why don't you make it a question and answer your own question.  Perhaps someone else can add to any any advantage or disadvantage of it.
Comment: @ToddWilcox: While it might be possible to strum the strings 1ms apart, that would seem unusually fast.  If the time between the first and last strings is 0.1 second, that would represent a spacing of 20msec.  If the first note is a 110hz A, that's more than two full waves.
Comment: @RockinCowboy: I wrote up http://music.stackexchange.com/questions/9468/what-guitar-tunings-allow-many-chords-without-fretting-between-live-strings/9469#9469 some time ago.  The basic idea is that if one wants to have the root of a chord be an octave below the fourth-string note, that will be easiest if one is playing that note adjacent to the fourth string.


fluentd and grok parser, add a key value

Question: I use an input syslog and the parser with grok expressions in fluentd.
It works well, but I would like to add a key in the fluentd parsed message.
The key would be the whole message itself. example with raw key:
<code>{
time: grokked time
host: grokked hostname
...
raw : the whole raw message,
}
</code>
how to do that ?
Answer: Add another filter:
<code> <filter **>
   @type record_transformer
   enable_ruby
   <record>
     raw ${record["message"]}
   </record>
 </filter>
</code>
Answer: yep I got it working at the same time with
<code><filter syslog>
  @type record_transformer
  enable_ruby
  <record>
    raw ${record}
  </record>
</filter>
</code>


The classification of irreducible representations of finite and compact Lie groups over $\mathbb{C}$

Question: I just started reading a few lecture notes on representation theory and I was wondering about a big picture that one should keep in mind while reading through these lecture notes.
Have all (finite-dimensional) irreducible representations of finite groups and compact Lie groups over $\mathbb{C}$ been classified in some way?
I am guessing that all (finite-dimensional) irreducible representations of a general Lie group haven't yet been classified, or have they?
Thank you.
Comment: A first problem with all finite groups is that those groups themselves have not been classified (only the simple ones have been, and that story is quite long enough as it stands). The usual way to get out of the implied difficulty (beacuse finite groups are Lie groups) when discussing Lie groups is to focus attention on _connected_ Lie groups. The representation theory of connected compact _or_ complex _reductive_ matrix Lie groups is quite satisfactory. Here "reductive" means having no nontrivial _normal_ subgroup consisting of unipotent matrices. Beyond that, life is harder.
Comment: What do you mean by classified? Like for every finite group all its reps are known? Then no way.
Comment: @SteveD I see. Thanks Steve!
Comment: @MarcvanLeeuwen This is helpful; thank you.
Comment: @MarcvanLeeuwen you should your comment to be an answer. I think it would suffice
Comment: @PeterPatzt: done.
Answer: A first problem with all finite groups is that those groups themselves have not been classified (only the simple ones have been, and that story is quite long enough as it stands). The usual way to get out of the implied difficulty (beacuse finite groups are Lie groups) when discussing Lie groups is to focus attention on connected Lie groups. The representation theory of connected compact or complex reductive matrix Lie groups is quite satisfactory. Here "reductive" means having no nontrivial normal subgroup consisting of unipotent matrices. Beyond that, life is harder


Using an address field widget on a custom form and storing data

Question: I have a Subscription custom entity and I would like to use the default entity form for administration tasks and a custom multistep form for the subscription process.
I added an address field to my Subscription entity and I would like to use the widget in one of the custom form steps.
I was expecting I could use something like '#type' => 'widget_id' plus some widget configuration, but it does not seem to be so simple as this answer points out.

a widget and a form element are two different things that are used in different cases; consider a widget a more specialized type of form element.

What would be the right approach then? In the field_attach_form change record a comment suggests
$display = EntityFormDisplay::collectRenderDisplay($entity, 'default');
$display->buildForm($entity, $form, $form_state);

How do I get just my address field? Form display modes?
And then, how do I deal with validating and storing the data properly?
Answer: You can limit the $form array's elements by setting their #access property to FALSE.
The validation and storing should be handled by the form for the corresponding entity by itself.
Comment: Thanks, @rémy, I was hoping for a more explicit method. Altering a whole form just to get a field seems a bit of a work-around, but you may well be right about this being the _most proper_ method currently available. I will wait a few days before accepting your answer to see if we get some other ideas.
Comment: Thanks again. At the end I ended up using `$display->buildForm` and then restricting access with an admin permission check on some fields.


Multiline names (x labels) in boxplot

Question: In R, I would like to give multiline names to some data sets in boxplot, like this:
boxplot(rnorm(10), rnorm(10, mean=2), names=c("Normal", "Shifted\n*"))

Here, the names seem to be aligned with their bottom lines, which causes the text to overlap with the axis.  How can I have multiline names which simply extend to the bottom instead of upwards?
Comment: Hi quazgar. The question seems to be only about R which makes it off-topic here but on-topic on [SO](http://stackoverflow.com/).
Comment: After reading the **R** tag info, I agree.  Can the question be moved over or should I add the question there manually?
Answer: This seems to do what you want, or at least very close:
boxplot(rnorm(10), rnorm(10, mean=2))
mtext(text=c("Normal", "Shifted\n*"),
      side = 1, line = c(2,3), at = c(1,2))

Multiline names (x labels) in boxplot


{ : missing value where TRUE/FALSE needed

Question: Here is my code:
tst <- data.frame(ref=c("A", "T", "C", "C", "G", "G"),
                      alt= c("AAA", "T", "A", "ATCGA", "G", "A"))
for(i in 1:nrow(tst)){
  if(tst[i,2] == "A"){
    tst <- tst[-i,]
  }
}

but I received this error
:
Error in if (tst[i, 2] == "A") { : missing value where TRUE/FALSE needed
Now I don't know how to solve it,
Thanks for any help
Comment: could you explain what you want to achieve? :)
Comment: What is the point of `-i` in the loop? Do you want to get rid of the line with **A** inside the second column? If it is the case `tst[tst[,2]!='A',]` solves the issue. No need a loop.
Comment: As a general rule, one should never use a negative index in loops, especially if it is for removing rows. Rather you should filter them like in the comment above by @maydin.
Comment: There might be better ways to achieve your goal instead of a loop. What is your expected output for the data shared?
Answer: When i=3, one has tst[i,2] == "A", so tst is transformed: tst <- tst[-3,]. Originally, tst has 6 rows, but now it has only 5 rows. And you get the 'missing value' message when i reaches 6, because there's no row 6 anymore.


From $[0,1]\times [0,1]$ construct the Klein bottle

Question: The argument by Wikipedia is enough or complete for the solution of the exercise?

Exercise: From $[0,1]\times [0,1]$ construct the topological space known as Klein bottle.

Wikipedia says
...More formally, the Klein bottle is the quotient space described as the square $[0,1] × [0,1]$ with sides identified by the relations $(0, y) \sim (1, y)$ for $0 ≤ y ≤ 1$ and $(x, 0)\sim  (1 − x, 1)$ for $0 ≤ x ≤ 1.$
Comment: What do you mean "enough or complete"?
Comment: Proof of what exactly?
Comment: Do you mean you want a proof that [this](https://en.wikipedia.org/wiki/File:Surface_of_Klein_bottle_with_traced_line.svg) is the same as [this](https://en.wikipedia.org/wiki/File:Klein_Bottle_Folding_1.svg)? That would require a formal definition of the former. On the other hand, the latter does have a formal definition and it is exactly what you've quoted.
Comment: I am quite lost here I also thought about drawing the construction of the klein bottle. I don't know maybe I need to do mathematical things.
Comment: @TrevorGunn well I was expecting something like a proof, and not just a description about the klein bottle. Maybe it's already a proof :) idk
Comment: @TrevorGunn A proof about the construction from the square to the klein bottle, things related to homeomorphism maybe?
Comment: @TrevorGunn Do you think the argument from Wikipedia it's a good answer?
Comment: If you want to prove that Wikipedia's construction is the same as a Klein bottle, you'd have to start with a definition of a Klein bottle other than the Wikipedia construction.
Comment: @TrevorGunn Since my professor didn't give me the formal definition of the former, I don't think that's the way to solution this exercise.
Answer: You take the unit square and identify opposite sides to get a cylinder.  Then go to identify the two circles at the opposite ends of the cylinder, like you were going to make a donut (torus), but, twist one of the circles $180^0$ before identifying...
Answer: Well, that answer looks just fine as I see it. But if you want more detail, you can extend on the idea given by Wikipedia. I will call $[0,1]=I$ for short.
We start with the square $[0,1]\times [0,1]=I^2$. We define an equivalence relation $\sim$ on it, the one generated by $(0,y)∼(1,y)$ for $0≤y≤1$ and $(x,0)∼(1−x,1)$ for $0≤x≤1$ (verify it is an equivalence relation).
Let $g:I^2\rightarrow I^2/\sim$ be the canonical quotient map, and give $I^2/\sim$ the quotient topology with respect to $g$. Geometrically you are identifying or "gluing" the sides of the square as follows:

You then have a completely defined topological space (the Klein bottle) built from the square $I^2$.
Comment: The quotient topology makes the identified point to be the same in the quotient, and makes close points to them to be close as well in the quotient. Imagine you live in that space; you are standing at $(0, 1/2)$ and you walk across the segment $(x, 1/2)$. Once you reach $(1, 1/2)$ you are in fact right where you started, for these two points are the same in this world. The quotient topology also made that path continuous.
Comment: How is $g$ given or defined? I mean how is the map of $g$?
Comment: $g(x,y)$ is the equivalence class of $(x,y)$ under the equivalence relation $\sim$ previously defined. I use the notation: $g(x,y)=[(x,y)]$.
Comment: This construction is usually given as the definition of the Klein bottle. It would be useful if you say what is the definition you want to work with in your question. Or maybe your professor just wanted you to formalize the idea of gluing the sides of the square we all know, using the notions of topological quotient.
Comment: Yes maybe just to formalize. Why to give the quotient topology?
Comment: I see, thank you for your answer.