text:
Q: I can't run a built Angular project - ERESOLVE unable to resolve dependency tree I'm following a tutorial of Angular and I wanted to run a project built by the instructor.
This is what I do to run it (I found these steps in the 'how-to-use' file)

How to use
Run "npm install" inside this project folder to install all
dependencies.
Make sure you use the latest version of the CLI (upgrade guide below)
Run "ng serve" to see the app in action (try "npm start" in case "ng
serve" fails).
Feel free to compare it with your project code to spot any errors you
might have.
How to upgrade the CLI
Run the below commands - only use "sudo" on Mac/ Linux.
sudo npm uninstall -g angular-cli @angular/cli
npm cache clean --force
sudo npm install -g @angular/cli

Upgrading the CLI works just fine, but when I move to the npm install command I get these errors:
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: my-first-app@0.0.0
npm ERR! Found: jasmine-core@3.6.0
npm ERR! node_modules/jasmine-core
npm ERR!   dev jasmine-core@"~3.6.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer jasmine-core@">=3.8" from karma-jasmine-html-reporter@1.7.0
npm ERR! node_modules/karma-jasmine-html-reporter
npm ERR!   dev karma-jasmine-html-reporter@"^1.5.4" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See /Users/t/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/t/.npm/_logs/2022-09-28T12_08_00_585Z-debug-0.log

Here's my package.json:
{
  "name": "my-first-app",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^11.0.5",
    "@angular/common": "^11.0.5",
    "@angular/compiler": "^11.0.5",
    "@angular/core": "^11.0.5",
    "@angular/forms": "^11.0.5",
    "@angular/platform-browser": "^11.0.5",
    "@angular/platform-browser-dynamic": "^11.0.5",
    "@angular/router": "^11.0.5",
    "bootstrap": "3.3.7",
    "rxjs": "^6.6.3",
    "rxjs-compat": "^6.0.0",
    "tslib": "^2.0.3",
    "zone.js": "^0.10.3"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.1100.4",
    "@angular/cli": "^11.0.4",
    "@angular/compiler-cli": "^11.0.5",
    "@types/jasmine": "~3.6.0",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^12.19.9",
    "codelyzer": "^6.0.1",
    "jasmine-core": "~3.6.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "~5.1.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.4",
    "protractor": "~7.0.0",
    "ts-node": "~8.3.0",
    "tslint": "~6.1.0",
    "typescript": "~4.0.2"
  }
}

this is Angular.json
{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "my-first-app": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/my-first-app",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "node_modules/bootstrap/dist/css/bootstrap.min.css",
              "src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "my-first-app:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "my-first-app:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "my-first-app:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": [
              "styles.css"
            ],
            "scripts": [],
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "my-first-app-e2e": {
      "root": "e2e/",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "my-first-app:serve"
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "my-first-app"
}

A: The problem you are facing is an issue with your dependencies. One of your packages requires a jasmine-core version greater than or equal to 3.8 and your package.json is installing version 3.6. You just need to update it in package.json Here is a copy of your package.json with this change, note the version in jasmine-core. With this package.json you just need to run npm install and then npm start.
{
  "name": "my-first-app",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^11.0.5",
    "@angular/common": "^11.0.5",
    "@angular/compiler": "^11.0.5",
    "@angular/core": "^11.0.5",
    "@angular/forms": "^11.0.5",
    "@angular/platform-browser": "^11.0.5",
    "@angular/platform-browser-dynamic": "^11.0.5",
    "@angular/router": "^11.0.5",
    "bootstrap": "3.3.7",
    "rxjs": "^6.6.3",
    "rxjs-compat": "^6.0.0",
    "tslib": "^2.0.3",
    "zone.js": "^0.10.3"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.1100.4",
    "@angular/cli": "^11.0.4",
    "@angular/compiler-cli": "^11.0.5",
    "@types/jasmine": "~3.6.0",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^12.19.9",
    "codelyzer": "^6.0.1",
    "jasmine-core": "~3.8.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "~5.1.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.4",
    "protractor": "~7.0.0",
    "ts-node": "~8.3.0",
    "tslint": "~6.1.0",
    "typescript": "~4.0.2"
  }
}


text:
Q: angular.js:14077 TypeError: Cannot read property 'getAllContacts' of undefined Basically I have a factory that pull the whole content in both tables (contacts and organizations)
I have this factory:
(function () {
    angular.module('appContacts')
        .factory('dataService', ['$q', '$http', dataService]);

    function dataService($q, $http) {

        return {
            getAllContacts: getAllContacts,
            getAllOrganizations: getAllOrganizations
        };

        function getAllContacts() {

            return $http({
                method: 'GET',
                url: 'api/allcontacts',
            })
            .then(sendResponseData)
            .catch(sendGetBooksError)
        }

        function getAllOrganizations() {

            return $http({
                method: 'GET',
                url: 'api/organizations',
            })
            .then(sendResponseData)
            .catch(sendGetBooksError)
        }

        function sendResponseData(response) {
            return response.data;
        }
        function sendGetBooksError(response) {
            return $q.reject('Error retrieving contact(s). (HTTP status: ' + response.status + ')');
        }
    }
})();

And I call it from this Controller:
(function () {
    "use strict";
    angular.module('appContacts')
        .controller('contactsController', ['$q', 'dataService', '$http', contactsController]);

    function contactsController($q, $http, $state, dataService) {
            var vm = this;
            vm.allcontacts = [];
            vm.contacts = [];
            vm.organizations = [];
            vm.phones = [];

            // Load all organizations
             dataService.getAllOrganizations()
                .then(vm.organizations = getAllOrganizations)

            // Load all contacts
            dataService.getAllContacts()
                .then(vm.allcontacts = getAllContacts);
//more stuff

But I get the error:
    angular.js:14077 TypeError: Cannot read property 'getAllContacts' of undefined
Any Idea what do I do wrong?

A: Your injection is not correct. Injected services and factories must be aligned (injected in the same order that they are referenced):
.controller('contactsController',['$q', 'dataService', '$http', contactsController])

function contactsController($q, $http, $state, dataService)

This means that $q is(correctly) '$q', $http is 'dataService', $state is '$http', and dataService is not defined. (You are also missing the '$state' injection)
This is what you want:
.controller('contactsController',['$q', 'dataService', '$http', '$state', contactsController])

function contactsController($q, dataService, $http, $state)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to solve this graph problem in WolframAlpha? I need to input this problem in WolframAlpha:

Write an equation of the line containing the given point and parallel to the given line: $(8,-8)$, $7x+8y=5$.

The answer is $7x+8y=-8$ but I'm not sure how to format it so that I get that answer.

A: I used the guess until I get it right approach.
tangent line to 7x+8y=5 through (8,−8)

which resulted in:

A: You need only know that the slope of a line parallel to the given line is equal to the slope of the given line.  Can you figure out the slope of you're given line?
$$7x + 8y = 5 \iff 8y = -7x + 5 \iff y = \dfrac{-7}{8}x + \dfrac 58$$
Now the original equation is in the form $$y = mx + b,\quad\text{where}\;\;m = -\dfrac 78\;\;\text{is the slope, and }\;\;b = \dfrac 58\;\;\text{is the y-intercept.}$$
Then you can use the point-slope form of an equation, and some algebra, to obtain the given answer, $$(y - y_0) = m(x - x_o)$$ where $(x_0, y_0) = (8, -8)$ and $m = -7/8$:
$$y-(-8) = -\dfrac 78(x - 8) $$ $$ \iff y+ 8 = -\dfrac{7}{8} x + 7 $$ $$\iff 8y + 64 = -7x + 56 $$ $$\iff 8y + 7x = -8$$
To graph the equation using only the slope you found above and the given point, ask Wolfram Alpha for the "equation of the line with slope $-7/8$ and going through the point $(8, -8)$."


text:
Q: Removing slowmode with slowmode command Alright so I have a slowmode command for my discord bot, setting the slowmode works fine, but I have made it so if there is no argument it will just set slowmode to 0 (no slowmode), that is the only part that is not working.
Code for removing the slowmode:
 if (!args[0]) {
            message.channel.setRateLimitPerUser('0');
            message.channel.send('Slowmode has been turned off for this channel')
        }

This is the full code to the command:
const Discord = require('discord.js');
const ms = require('ms')

module.exports = {
    name: 'slowmode',
    aliases: ['sm'],
    description: "sets a slowmode for a channel",
    execute(Client, message, args){
        if(!message.member.hasPermission("MANAGE_CHANNELS")) return message.reply("[ERROR] Invalid permissions. Permissions missing: BAN_MEMBERS. If you think this is a mistake, please contact support.")

        if (!args[0]) {
            message.channel.setRateLimitPerUser('0');
            message.channel.send('Slowmode has been turned off for this channel')
        }

       const rawTime = args[0]
       const time = ms(rawTime)

       if (isNaN(time)) return message.channel.send("[ERROR] The time you provided is not a number.")
       if (time < 1000) return message.channel.send("[ERROR] You cannot put the slowmode under 1 second.")
       if (time > 21600) return message.channel.send("[ERROR] You cannot put the slowmode over 6 hours. ")

       message.channel.setRateLimitPerUser(time / 1000);
       message.channel.send(`Slowmode has been set to ${args[0]} for this channel.`)

    }
}

This is the error that I get when I run the command with no argument:
Error: val is not a non-empty string or a valid number. val=undefined
    at module.exports (C:\Users\Owner\Desktop\Venom\node_modules\ms\index.js:34:9)
    at Object.execute (C:\Users\Owner\Desktop\Venom\commands\slowmode.js:18:28)
    at module.exports (C:\Users\Owner\Desktop\Venom\events\guild\message.js:10:25)

A: You forgot to return from the function when args[0] is undefined. The error comes from a library, when you supply a wrong value to the ms() function.
Also it would make more sense to pass a Number instead of String to the .setRateLimitPerUser() method. As said in the docs.
if (!args[0]) {
    message.channel.setRateLimitPerUser(0);
    message.channel.send('Slowmode has been turned off for this channel');
    return;
}


text:
Q: How to set width for modal in flutter (modal_bottom_sheet package) I'm trying to have the modal have spacing on the sides as compared to it taking up the entire width but I'm having a hard time finding a solution with this package as it doesn't seem to have a width parameter that I can work with.
Current result:

Desired result:

Notice how on the desired result, there is the spacing between the sides of the modal and the device edges.
Here's the code I'm working with for the current result:
Future<dynamic> preFocusModal(BuildContext context) {
  return showMaterialModalBottomSheet(
    context: context,
    builder: (context) => Container(
      height: 300,
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.secondary,
        borderRadius: BorderRadius.all(
          Radius.circular(10),
        ),
      ),
    ),
  );
}

I have tried adjusting the width of the child Container but that didn't work (figured it might because that's how it seems I can set height)
Also tried wrapping the modal in Padding but that would require another method extraction as the return type needs to be Future for the modal. This might work but I want to see if there's a more optimal solution.
Thank you!
Solution:
Future<dynamic> preFocusModal(BuildContext context) {
  return showMaterialModalBottomSheet(
    backgroundColor: Colors.transparent,
    context: context,
    builder: (context) => Padding(
      padding: EdgeInsets.all(15),
      child: Container(
        height: 400,
        decoration: BoxDecoration(
          color: Theme.of(context).colorScheme.secondary,
          borderRadius: BorderRadius.all(
            Radius.circular(30),
          ),
        ),
      ),
    ),
  );
}

A: Inside the container, add another container as child and add a margin.
And set Colors.transparent as the color of outer container.
Then adjust the properties of inner container to achieve desired output.


text:
Q: Is a meromorphic function on the Riemann Sphere completely determined modulo scalar by its zeroes and poles and their orders? Let's say that all I know about a function $f$ is that it is meromorphic on $\mathbb{C}_\infty$, and that $\{z_i\}$ is the sets of zeroes of $f$, each one of order $n_i$ and $\{\lambda_j\}$ its set of poles, each one of order $m_i$. Does $f$ gets completely determined, modulo a constant scalar, with only this information?
I think that I can show this as it follows: if $f$ is meromorphic on the Riemann Sphere, then it is a rational function. If $\alpha :\mathbb{C}_\infty\rightarrow\mathbb{C}$ is a holomorphic function, then it is constant. If $\alpha$ is not identically zero, then $\alpha f$ is a meromorphic function over $\mathbb{C}_\infty$ with the same set of zeroes and poles with the same orders.
It could possibly be a trivial fact but I'm attending some Riemann Surfaces lectures without having a formal graduate course in Complex Analisys in one variable. Please criticize this!

A: A hint: Given such an $f$, the set of zeros $z_i\in{\mathbb C}$ and their orders $n_i$, as well as the set of poles $\lambda_j\in{\mathbb C}$ and their orders $m_j$, define the rational function
$$g(z):={\prod_j (z-\lambda_j)^{m_j}\over\prod_i (z-z_i)^{n_i}}\ f(z)\qquad(z\in{\mathbb C}) .$$


text:
Q: Running pre deployment Grunt tasks on Heroku I am fiddling with heroku to deploy my nodejs based application. The problem is I want to run some pre deployment scripts which contain grunt tasks. These tasks basically minify css and js files and perform some more operations like updating the version of the application in files etc.
The only way that I can think of now is to commit the minified files in the git repo itself and deploy.
This is not a good idea (for me at least) as it unnecessarily maintains revision history of minified files which is a total waste.
Please help.

A: I've seen people recommending creating a throwaway git branch for deployments.  In the second of the above comments: How to deploy node app that uses grunt to heroku.
Personally I prefer to execute a grunt task(s) that packages my app and copies it to a directory outside my source tree/repo.  Usually the target directory contains a throwaway git repository that I add to just to be able to do the push to heroku.
My workflow is to do any file processing I need to and then to copy the results to the output directory, skipping unnecessary files, and adding environment specific configurations and artifacts.   A series of grunt tasks does this and the final one adds everything to the local reopo, sets the heroku remote (I have several apps on heroku to cover production, staging, and a sandbox usually used to look at old versions of things), and finally doing the push.


text:
Q: How do I add an image from the web to my html site? When I add an image to my html website, the image doesn't appear, instead showing the alt text with the icon of a broken image. It's an image I found on the internet and I'm trying to display it on my website without having to download the image and add it through my own directory.
Here's the code that I used:
<img scr="https://yt3.ggpht.com/a/AGF-l7-Aq7ODH-bBOoENURKWZ-EEJxjpTQMvluC8-A=s900-c-k-c0xffffffff-no-rj-mo" alt="Shark Dude"/>

I have been struggling with this for a couple of hours now and I really don't get what is wrong? If you press on the link, it will show you a picture and nothing else. I basically found this picture on google and then I right-clicked on it and pressed copy image web address.
I hope someone can help!

A: The attribute your want on the img tag is src, not scr. This is shorthand for source. You can find a reference for img (and the other available HTML tags) at https://developer.mozilla.org/en-US/docs/Web/HTML/Element/


text:
Q: C - Child process reads from pipe twice in a row instead of reading once and then blocking I need to build two programs: a server and a client in C, that implement the following:

*

*When I start the server, he creates a named pipe (O_RDONLY) blocking itself until a client connects.

*The client sends a msg to the client using the named pipe opened with O_WRONLY, unlocking the server.

*The server receives the message and then passes that message to a child (using an anonymous pipe) who prints the message on the screen.

*

*If the child process isn't created, the parent creates one

*The child is supposed to read from the anonymous pipe 1 message PER CLIENT. Meaning that the child is supposed to read from the anon. pipe, print the msg, then block until the next client.

The issue I'm having right now is that sometimes the child will read and print the message TWICE, when there was only 1 connected client.
I've been at this for 8 hours already and I can't figure this out. Please someone help me with this, I'm going crazy over here. This is  the code I have so far:
Client
int main(int argc, char* argv[]){
int pPedido;
pPedido = open("pedido",O_WRONLY);
char buffer[6] = "ABCDE";
write(pPedido,buffer,6);
printf("FECHOU\n");
return 0;
}

Server
int main(int argc, char* argv[]){
int exists = 0;
int pipeID[2];
int pPedido;
char buffer [100];
mkfifo("pedido",0666);

while(1){
    pPedido = open("pedido",O_RDONLY);
    read(pPedido,buffer,6);

    if(exists == 1){
        write(pipeID[1],"ABC",4);
    }
    else{
        pipe(pipeID);
        if(fork() == 0){
            char bufferzito[100];
            while(1){
                read(pipeID[0],bufferzito,4);
                printf("%s\n",bufferzito);
            }
        }
        else{
            write(pipeID[1],"ABC",4);
            exists = 1;
        }
    }
}
return 0;
}

These are the includes I used. I think some of them are not necessary though.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

A: You are not checking the return value from open or from read. Both of these functions can return -1 to indicate an error.
Probably what is happening is that on the second iteration of the server while loop, either the open or the read returns immediately with a return value of -1 (an error) so your loop executes again.
After calling read or open, check the return value, and also check errno if it returned -1.
You are also opening the same fifo again and again on each iteration of the loop, without ever closing it.

A: I have tested the following solution and it works.
The problem seems to be that client is exiting without closing the pipe.
Somehow this results in a second read that is writing 0 bytes to the buffer. Getting 0 as the return value on read means EOF according to the documentation. I'm not sure why we are not getting the second read the first time the client is connecting.
To handle this situation you can do one of the two things. You probably should do both of them though.
On the server side check the return value of the read call
...
int n = read(pPedido,buffer,6);
if(n==0) continue;
...

On the client side close the pipe before exiting
...
printf("FECHOU\n");
close (pPedido);
return 0;

Either one by itself will fix the problem. But I'd recommend doing both.


text:
Q: I have an image data and metadata containing the description of the image, how can i use both image image and metadata to train the images I need to build a classifier of skin lesions and have image dataset along with metadata which has description consisting of the classification.
any help as to how to match the data and images and use both in training my convolutional neural network

A: Seems like you are asking how to incorporate non-numeric data in your metadata in the Neural Network you are trying to train. Hopefully, you will find this document on tf.feature_columns helpful. It will help you incorporate categorical, ordinal, etc. as numeric columns.
To train the model with both kind of information, one way would be:

*

*Apply CNN to your images and get a dense representation

*Simultaneously, build another NN to pass your metadata through

*Concatenate the two resultant Tensors from both NNs and then pass it all through a softmax

Hopefully this should help.
Now the above mentioned tf.feature_columns is no longer recommended for new code. Instead of this use Keras preprocessing layers.


text:
Q: Mongodb timeout error I've a nodejs application. When it start it connects to a mongodb listening at 127.0.0.1:27017 (using mongoose). The application uses 5 separate collections connected with one key from primary collection such as (user._id where 'User' is the primary collection). When application start I want to populate database with let's say 100K records. So I wrote a for loop for 100K iterations as shown below,
  for (var ii=0; ii < count; ii++) {
    async.series([
      function(callback) {
        //Build User record
        var user = new User();
        user.email = ii.toString() + '@example.com';
        user.save(function(err, data) {
          if (err) {
            console.log(err);
            return callback(err, null);
          }
          user_id = data._id;
          console.log('New User:' + user_id);
          u_count++;
          callback();
        });
      },
      function(callback) {
         //Save collection 2 information about newly saved user (user_id);
         var photo = new Photo();
         photo._user = user_id;
         photo.save() {
           ......
           callback();
         }
      },
      function(callback) {
         //collection 3 ...
         ....
      }
      //3 more collection save calls in series
    ), function(err) { //Final callback for each iteration
         ...
      });
    }); //end of async.series()
  } //end of for loop

If the count=10000, the database populates correctly but if I increase that number to 100K, I start to get following errors,
{ [MongoError: connection 4 to 127.0.0.1:27017 timed out]
  name: 'MongoError',
  message: 'connection 4 to 127.0.0.1:27017 timed out' }
   Saving Photo: Internal error while saving employee record
  Error while running async.seriesMongoError: connection 4 to 127.0.0.1:27017 timed out

'4' I believe is the number of connection with mongodb. This varies, depending when (or which async operation is executing) you get this error.
Im not able to track this error. Any help is appreciated.
--Atarangp


text:
Q: How to print a page in Angular 4 with TS I have an web app while in some pages I need to make a printer to print the page but I have a side bar and the rest ist the page for a component, how it is possible to not print the sidebar only this component, I have used in TS this code.
print() {
window.print();
}

Html code starts from this one.
div class="container">
//Here I have all the HTML source

A: first of all assign an id to that component,
then:
const printContent = document.getElementById("componentID");
const WindowPrt = window.open('', '', 'left=0,top=0,width=900,height=900,toolbar=0,scrollbars=0,status=0');
WindowPrt.document.write(printContent.innerHTML);
WindowPrt.document.close();
WindowPrt.focus();
WindowPrt.print();
WindowPrt.close();

A: You can try this solution.

html file

//Here I have all the HTML source

//Here I have all the HTML source

<button (click)="printComponent('component1')">Print</button>

ts file

printComponent(cmpName) {
     let printContents = document.getElementById(cmpName).innerHTML;
     let originalContents = document.body.innerHTML;

     document.body.innerHTML = printContents;

     window.print();

     document.body.innerHTML = originalContents;
}

A: In the side bar component scss file or css file...you can hide it when you are printing using media queries:
@media print {
  :host {
    display: none;
  }
}

A: There is no Direct window print function in typescript We need to create a new function with print() and inside that print function write javascript print function as shown below

in Ts File
print() {
window.print();
}


text:
Q: Exporting Test Cases from Visual Studio Team Services? I don't see anywhere where I can simply export all the test cases from my instance of Visual Studio Team Services. This is not to be confused with regular Team Foundation Server. This is the hosted version by Microsoft and is a SaaS application.
Any way to export the test cases into Excel?

A: I suggest you to use this tool Export Test Cases From TFS. (Dedicated for Excel)  This tool is good because you can have result and steps.
You can also use Test Scribe (Dedicated for Work)
Or you can use a WIQL query and export to Excel.


text:
Q: Laravel function in User model that will be called for User::all() Imagine I have this function in User model:
public function loadOrderStatus(){
    $this->load(['status' => function ($query) {
        $query->ofTranslatedStatuses();
    }]);
}

This function works fine for single model instance like : User::first()
but how this function can be used with User::all() ?

A: You can use a scopeQuery in the User model
public function scopeStatusAll($query)
{
    return $query->with(['status' => function ($query) {
        $query->ofTranslatedStatuses();
    }]);
}

call it with
User::statusAll()->get();

Or you could put a static function in User model
public static function statusAll()
{
    $users = User::all();

    return $users->load(['status' => function ($query) {
        $query->ofTranslatedStatuses();
    }]);
}

call it with
User::statusAll();


text:
Q: Não estou conseguindo imprimir as notas, que seria n1 e n2 da lista, não sei se o parametro enviado para a função está correto #include <stdio.h>
#include <stdlib.h>

typedef struct nota n;

struct nota
{
    float n1;
    float n2;
    float mf;

    struct nota *prox;

};

void imprime(n *le)
{
    while(le != NULL)
    {
        printf("%.0f",le -> n1);
        printf("%.0f\n",le -> n2);
        le = le -> prox;
    }
    printf("\nFIM");
}

int main()
{
    n *paux;

    int qt;

    printf("Quantidade de notas: ");
    scanf("%d",&qt);

    paux = (n*)malloc(sizeof(n));

    for(int i=0;i<qt;i++)
    {
        printf("Nota 1: ");
        scanf("%f",&paux -> n1);

        printf("Nota 2: ");
        scanf("%f",&paux -> n2);

        paux -> mf = (paux -> n1 + paux -> n2)/2;

        paux -> prox;

        printf("\n");
    }

    imprime(paux);

    return 0;
}

A: O problema que eu estou vendo é que o seu ponteiro auxiliar é sempre o mesmo. Para criar uma lista, a cada iteração do seu for, você deveria alocar um novo espaço na memória e atribuir esse espaço para o seu ponteiro auxiliar
Por exemplo:
int main()
{
    // Crio o nodo "inicial" apenas para manter registro da posição inicial da lista
    n *inicial = malloc(sizeof(n));
    n *paux = inicial;

    int qt;

    printf("Quantidade de notas: ");
    scanf("%d", &qt);

    for (int i = 0; i < qt; i++)
    {
        printf("Nota 1: ");
        scanf("%f", &paux->n1);

        printf("Nota 2: ");
        scanf("%f", &paux->n2);

        paux->mf = (paux->n1 + paux->n2) / 2;

        if (i + 1 == qt)
        {
            // Se for o ultimo item da lista, atribuo NULL para o ponteiro do próximo nodo
            paux->prox = NULL;
        }
        else
        {
            // Caso contrário, aloco um novo espaço na memória para o próximo nodo, e movo o ponteiro auxiliar para essa posição
            paux->prox = malloc(sizeof(n));
            paux = paux->prox;
        }

        printf("\n");
    }

    // Envio o nodo com a posição inicial da lista
    imprime(inicial);

    return 0;
}

Com ajuda de ponteiros apontando para ponteiros, também é possível se livrar da condição if. Note que o resultado desse código é o mesmo, mas um código capaz de tratar a exceção como norma, geralmente é considerado mais elegante.
int main()
{
    n *inicial = NULL;
    n *aux;
    n **paux = &inicial;

    int qt;

    printf("Quantidade de notas: ");
    scanf("%d", &qt);

    for (int i = 0; i < qt; i++)
    {
        (*paux) = malloc(sizeof(n));
        aux = *paux;

        printf("Nota 1: ");
        scanf("%f", &aux->n1);

        printf("Nota 2: ");
        scanf("%f", &aux->n2);

        aux->mf = (aux->n1 + aux->n2) / 2;
        aux->prox = NULL;

        paux = &aux->prox;

        printf("\n");
    }

    imprime(inicial);

    return 0;
}


text:
Q: Laravel 2 tables has pivot table and 1 table has id column from the other field I have tables USERS, DESIGNATIONS and JOBS where in USERS AND DESIGNATION has pivot table. And JOBS has relation to DESIGNATIONS with column in the table named designation_id.
What I want is if the USER logged in they can only see the JOBS(has designation_id in the table) that under on his DESIGNATIONS. Please see below code. Thank you
TABLE STRUCTURE
designation_user
id | user_id | designation_id

jobs table has
designation_id

USER MODEL
public function designations() {
   return $this->belongsTo(Designation::class, 'designation_user');
}

DESIGNATION MODEL
public function users() {
   return $this->belongsTo(User::class, 'designation_user');
}


text:
Q: grep erroring on globbing grep: f: no such file or directory When I grep with globbing I get the error: "grep: f: no such file or directory" and it doesn't give me any valid resluts, just the error.
ie: grep asdf *
What I know:
It's only if I use * by itself
If I use the full path it works, ie 'grep asdf /home/user/*'
It's grep egrep and fgrep
There is not a file named 'f' hidden or otherwise.
It is any user, just in this one directory (the home directory for my main user)
If I create a file named 'f' I get grep: asdf: No such file or directory, (asdf being whatever I am grepping for and it hangs indefinitely.
strace shows "open("f",O_RDONLY) no matter what I grep for.
This may not be the appropriate forum, but I use this command very often for work, it's automatic for me, and I hate having to redo the command with the full path. I can't find any answers anywhere.


text:
Q: How to put TextField`s content type for Float on XCode? I've a TextField to user put a number value (Float or Double), but in most of cases it number is Integer, but I must show the value in Float format for example: 3.0, 2.5. When the user put a Integer, the value shows like: 2. How I set a way to TextField automatically put in decimal point value?
ps. In the options of content type not have a option to number.

This is the wrong way:

A: There is no inbox solution, you should do it manually with UITextFieldDelegate:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
   //customize your string here
}


text:
Q: Objective-C @synchronized object changes I am really fond of @synchronized-construct instead of using NSLocks, when I want that a data structure is only read or written by one thread at a time. However, when I want to change the whole object we are @synchronizing on, I am not sure if @synchronized is suitable. What I want to know, is whether these work the same way:
// version 1:

// segment 1:
@synchronized(self.obj) {
    self.obj = obj2;
}
// segment 2:
@synchronized(self.obj) {
    // some other stuff
}

// version 2:
// segment 1:
[objLock lock];
self.obj = obj2;
[objLock unlock];
// segment 2:
[objLock lock];
// some other stuff
[objLock unlock];

A: Instead you can set a property without nonatomic. The absence of nonatomic means, it is atomic.

Properties are atomic by default so that synthesized accessors provide robust access to properties in a multithreaded environment—that is, the value returned from the getter or set via the setter is always fully retrieved or set regardless of what other threads are executing concurrently.

For more info, see Apple documentation

A: A NSLock and a @synchronized call are basically the same thing, and are pretty much interchangeable. There are a few minor differences, which you probably don't need to care about for such a simple implementation - but do read up on them, because it's sort of interesting!
There's a good SO answer here that compares the two: How does @synchronized lock/unlock in Objective-C?


text:
Q: If the Terminator had killed Sarah Connor in 1984, would he have gone on a mass killing spree until he was destroyed? If the Terminator had completed his mission in 1984 by killing Sarah Connor, is it likely that he would have gone on a mass killing spree until he was destroyed by the police/military?
In other words, did Skynet give him a secondary mission other than just killing Sarah Conner and what was that mission?


text:
Q: Why Firefox and other browsers freeze while I'm trying to initialize multiple components but not on Chrome? On Firefox (version 67.0), I have a grid table to display data. I use a forEach() to create columns and rows from JSON data for the grid table. It's about 100 rows, 10 columns. During the creating row & column iteration, the browser is freezing, I can't do anything on the webpage. After the iteration, everything back to normal.
I have tried to do the same on different browsers: IE, Edge, Chrome (newest version). The freezing problem exists on IE, Edge excepts Chrome. During the iteration on Chrome, I can do other tasks on the webpage e.g click on a button, hover on columns, etc.
Why doesn't it happen on Chrome? Is it because Chrome uses a different engine?
How can I overcome this issue?
function initGridComponents() {
  let records = data.items;
  records.forEach((record) => {
    createColumnsType1(record);
    createColumnsType2(record);
    createColumnsType3(record);
  });
}

I expect it will work normally among browsers with freezing.

A: You can utilise the event queue to space out the operations and thus make your page more responsive while loading:
function initGridComponents() {
  let records = data.items;
  records.forEach((record) => {

    setTimeout(createColumnsType1, 0, record);
//             ^^^^^^^^^^^^^^^^^^     ^^^^^^
//               function handle     parameter
    setTimeout(createColumnsType2, 0, record);
    setTimeout(createColumnsType3, 0, record);
  });
}


text:
Q: Using isset() method to vaidate login form. PHP I was trying to create this login form to validate on the same page. it should hide the form once the login is validated. I have been testing is, but its not showing any error.
When i click on the submit button, it just refreshes the page.

    <?php
    $DisplayForm = TRUE;
    $errors = 0;

    if(isset($_POST['loginForm'])){
    include("dbconnect.php");
    if($DBConnect !== FALSE){
    $SQLstring = "SELECT userid, first_name, last_name FROM users WHERE username ='".
    $_POST['uname']. "' and password = '".md5($_POST['pass'])."'";
    $DisplayForm = FALSE;
    $QueryResult = @mysql_query($SQLstring, $DBConnect);
    echo mysql_error();
    if (mysql_num_rows($QueryResult)=== 0){
      echo "
The email address/password " .
      " combination is not valid.
\n";
      ++$errors;
      $DisplayForm = TRUE;
    }
    else
    {
      $DisplayForm = FALSE;
    }

    }

    }

    if ($DisplayForm)
    {?>

     <form id="form1" name="loginForm" method="post" action="index.php">

          Username:

      <input type="text" name="uname" id="textfield" />
      Password:

      <input type="password" name="pass" id="pass" />
      <input type="image" name="login" src="images/login.jpg" />

      Register

    </form>

    <?php }
    else {
        $Row = mysql_fetch_assoc($QueryResult);
      $userID = $Row['userid'];
      $userName = $Row['first_name']. " ". $Row['last_name'];
      echo "
Welcome back, $userName!
\n";
      }

     ?>

A: You don't have a submit button.
Add the following to your form :
<input type="submit" name="formSubmit" />

Then you can check in your first isset-line: isset($_POST['uname'] && $_POST['pass']);

A: You could not apply isset on <form>. Try to apply isset on input field
<?php

if(isset($_POST['uname'] && isset($_POST['pass'])) {

// .. foo

}

?>

Moreover, your form is never submitted. Add <input type="submit" value="Register" />

A: To check if something's been posted, you should instead add a hidden input field:
<input type="hidden" name="wasSubmitted" value="true">

Then check isset($_POST['wasSubmitted']), or $_POST['submitted'] == 'true'.
Only fields are contained in the $_POST[] superglobal.


text:
Q: How can I Draw rectangle in programmatically How can I draw rectangle(Oblique projection view) in programmatically(python) by giving height, width and depth.

A: Take a look at Python's turtle module, here is the v3.3 documentation. On top of height, width and depth, you will need to think about an angle for the projection - I think this is typically 30/45 degrees.
To get you started... adapting code by Y. Daniel Liang.
import turtle

w = 100
h = 50
d = 20
angle = 30

def drawRectangle(width, height):
    turtle.right(90)
    turtle.forward(height)
    turtle.right(90)
    turtle.forward(width)
    turtle.right(90)
    turtle.forward(height)
    turtle.right(90)
    turtle.forward(width)

turtle.penup()
turtle.goto(0, 0)
turtle.pendown()
drawRectangle(w, h)
turtle.left(angle)
turtle.forward(d)
turtle.right(angle)
drawRectangle(w, h)


text:
Q: how to write spacy matcher of POS regex Spacy has two features I'd like to combine - part-of-speech (POS) and rule-based matching.
How can I combine them in a neat way?
For example - let's say input is a single sentence and I'd like to verify it meets some POS ordering condition - for example the verb is after the noun (something like noun**verb regex). result should be true or false. Is that doable? or the matcher is specific like in the example
Rule-based matching can have POS rules?
If not - here is my current plan - gather everything in one string and apply regex
    import spacy
nlp = spacy.load('en')
#doc = nlp(u'is there any way you can do it')
text=u'what are the main issues'
doc = nlp(text)

concatPos = ''
print(text)
for word in doc:
    print(word.text, word.lemma, word.lemma_, word.tag, word.tag_, word.pos, word.pos_)
    concatPos += word.text +"_" + word.tag_ + "_" + word.pos_ + "-"
print('-----------')
print(concatPos)
print('-----------')

# output of string- what_WP_NOUN-are_VBP_VERB-the_DT_DET-main_JJ_ADJ-issues_NNS_NOUN-

A: Sure, simply use the POS attribute.
import spacy
nlp = spacy.load('en')
from spacy.matcher import Matcher
from spacy.attrs import POS
matcher = Matcher(nlp.vocab)
matcher.add_pattern("Adjective and noun", [{POS: 'ADJ'}, {POS: 'NOUN'}])

doc = nlp(u'what are the main issues')
matches = matcher(doc)

A: Eyal Shulman's answer was helpful, but it makes you hard code a pattern matcher, not exactly use a regular expression.
I wanted to use regular expressions, so I made my own solution:
    pattern = r'(<VERB>)*(<ADV>)*(<PART>)*(<VERB>)+(<PART>)*'
    ## create a string with the pos of the sentence
    posString = ""
    for w in doc[start:end].sent:
        posString += "<" + w.pos_ + ">"

    lstVerb = []
    for m in re.compile(pattern).finditer(posString):
        ## each m is a verb phrase match
        ## count the "<" in m to find how many tokens we want
        numTokensInGroup = m.group().count('<')

        ## then find the number of tokens that came before that group.
        numTokensBeforeGroup = posString[:m.start()].count('<')

        verbPhrase = sentence[numTokensBeforeGroup:numTokensBeforeGroup+numTokensInGroup]
        ## starting at character offset m.start()
        lstVerb.append(verbPhrase)


text:
Q: What would be possible uses for finding minimum zone flatness in 3D or higher dimensions? Let's start in 3D. Suppose $A\subset \Bbb R^3$ is a finite collection of points, the so-called minimum zone flatness is the minimised distance between two parallel planes that "sandwich" $A$ in between. And the minimum zone is the region sandwiched by such two planes.
This article proposes a highly efficient algorithm to accomplish the task of finding the minimum zone and minimum zone flatness for large datasets. In the introduction part, the author says

Flatness is one of the most fundamental geometric forms that
  are used in manufacturing to measure the quality of a machined
  surface.

Beyond this, however, I cannot think of any other situations in which finding the minimum zone of a dataset may be useful. And if we extend the task to higher dimensions ($\Bbb R^k, k\ge 4$), then I'm unable to imagine a single usage of finding such a minimum zone. Interestingly, though, finding the minimum zone seems to be an "opposite" task of finding the "maximum zone" formed by two separating planes in support vector machine.  But I don't see any way to relate it to SVM.
Could anybody enlighten me? Thanks!


text:
Q: Why the top few rows disappear after using query in google sheet?

Hi everyone,
I have 2 tabs in the google sheet:

*

*Form Responses (collecting the data from google form) [First screenshot]

*Query [2nd screenshot]

Based on the 2 screenshot above, may I know why I'm only able to get the data started from row 8 in Form Responses after using the QUERY function in google sheet?
As you can see from the 2nd screenshot, there is no Teacher 1, Teacher 2,Teacher 3, Teacher 4 although the Action are also Initial Entry.
I couldn't figure out the reason, hope to get some advise. Any help will be greatly appreciated!

A: Try using the optional headers argument and see if that helps?
=query('Form Responses'!A:AD, "Select A, B, C where C = 'Initial Entry' label A 'Timestamp', B 'Name', C 'Action'", 0)


text:
Q: How to optimize multiple left-joins SQL SELECT-query? Situation:
We have a database "base1" ~ 6 million lines of data, which shows the actual customer purchases and the day of purchase + the parameters of this purchase.
CREATE TABLE base1 (
User_id NOT NULL PRIMARY KEY ,
PurchaseDate date,
Parameter1 int,
Parameter2 int,
...
ParameterK int );

And also another database "base2" ~ 90 million lines of data, which actually shows the same thing, but instead of the day of purchase, a weekly section is used (for example: all weeks for 4 years for each client - if there was no purchase for N week, the client is still shown).
CREATE TABLE base2 (
Users_id NOT NULL PRIMARY KEY ,
Week_start date ,
Week_end date,
Parameter1 int,
Parameter2 int,
...
ParameterN int );

The task to do the following query:
-- a = base1 , b , wb%% = base2
--create index idx_uid_purch_date on base1(Users_ID,Purchasedate);
SELECT a.Users_id
-- Checking whether the client will make a purchase in next week and the purchase will be bought on condition
,iif(b.Users_id is not null,1,0) as User_will_buy_next_week
,iif(b.Users_id is not null and b.Parameter1 = 1,1,0) as User_will_buy_on_Condition1
--   about 12 similar iif-conditions
,iif(b.Users_id is not null and (b.Parameter1 = 1 and b.Parameter12 = 1),1,0)
as User_will_buy_on_Condition13

-- checking on the fact of purchase in the past month, 2 months ago, 2.5 months, etc.
,iif(wb1m.Users_id is null,0,1) as was_buy_1_month_ago
,iif(wb2m.Users_id is null,0,1) as was_buy_2_month_ago
,iif(wb25m.Users_id is null,0,1) as was_buy_25_month_ago
,iif(wb3m.Users_id is null,0,1) as was_buy_3_month_ago
,iif(wb6m.Users_id is null,0,1) as was_buy_6_month_ago
,iif(wb1y.Users_id is null,0,1) as was_buy_1_year_ago

 ,a.[Week_start]
 ,a.[Week_end]

 into base3
 FROM base2 a

 -- Join for User_will_buy
 left join base1 b
 on a.Users_id =b.Users_id and
 cast(b.[PurchaseDate] as date)>=DATEADD(dd,7,cast(a.[Week_end] as date))
 and cast(b.[PurchaseDate] as date)<=DATEADD(dd,14,cast(a.[Week_end] as date))

 -- Joins for was_buy
 left join base1  wb1m
 on a.Users_id =wb1m.Users_id
 and cast(wb1m.[PurchaseDate] as date)>=DATEADD(dd,-30-4,cast(a.[Week_end] as date))
 and cast(wb1m.[PurchaseDate] as date)<=DATEADD(dd,-30+4,cast(a.[Week_end] as date))

/* 4 more similar joins where different values are added in
DATEADD (dd, %%, cast (a. [Week_end] as date))
to check on the fact of purchase for a certain period */

 left outer join base1 wb1y
 on a.Users_id =wb1y.Users_id and
 cast(wb1y.[PurchaseDate] as date)>=DATEADD(dd,-365-4,cast(a.[Week_end] as date))
 and cast(wb1y.[PurchaseDate] as date)<=DATEADD(dd,-365+5,cast(a.[Week_end] as date))

Because of the huge number of Joins and rather big databases - this script runs for about 24 hours, which is incredibly long.
Main time, as the execution plan shows, is spent on "Merge Join" and view the rows of the table from base1 and base2, and insert the data into another base3 table.
Question: Is it possible to optimize this query so it works faster?
Perhaps using one Join instead or something.
Help please, I'm not that smart enough :(
Thanx everybody for your answers!
UPD: Maybe use of different type of joins (merge, loop, or hash) may help me, but can't really check this theory. Maybe someone can tell me whether it's right or wrong ;)

A: I assume that the base1 table stores information about the current week purchases.
If that is true, in the query conditions of joins you could ignore [PurchaseDate] parameter, replacing it with the current date constant instead. In that case your DATEADD functions will be applied to the current date and will be constants in the conditions of joins:
left join base1 b
on a.Users_id =b.Users_id and
DATEADD(day,-7,GETDATE())>=a.[Week_end]
and DATEADD(day,-14,GETDATE())<=a.[Week_end]

To have the query above running correctly you should limit b.[PurchaseDate] to the current day.
Then you could run another query, for the purchases made yesterday, and all DATEADD constants in join conditions corrected by -1
And so on, up to 7 queries, or whatever timespan the base1 table covers.
You could also implement grouping of [PurchaseDate] values by days, recalculate constants and make all of that in a single query, but I'm not ready to spend time creating it myself. :)

A: If you have recurring argument such as DATEADD(dd,-30-4,cast(a.[Week_end] as date)) for example, to make it SARGable you can create an index on it (SQL Server can't). Postgres can do this:
create index ix_base2__34_days_ago on base2(DATEADD(dd,-30-4, cast([Week_end] as date)))

Then an expression like the following would be SARGable as index on DATEADD(dd,-30-4, cast([Week_end])) would be utilized by your database, hence a condition like the following will be fast if you have an index like on the example above.
and cast(wb1m.[PurchaseDate] as date) >= DATEADD(dd,-30-4,cast(a.[Week_end] as date))

Note that casting PurchaseDate to date yields a SARGable expression, despite cast looking like a function, as SQL Server has special handling of datetime to date, an index on datetime field is SARGable even you search on datetime field partially (the date part only). Similar to partial expression like, where lastname LIKE 'Mc%', that expression is SARGable even if an index is for the whole lastname field. I digress.
To somewhat achieve the index on expression on SQL Server, you can create a computed column on that expression.., e.g.,
CREATE TABLE base2 (
  Users_id NOT NULL PRIMARY KEY ,
  Week_start date ,
  Week_end date,
  Parameter1 int,
  Parameter2 int,
  Thirty4DaysAgo as DATEADD(dd,-30-4, cast([Week_end] as date))
)

..and then create index on that column:
create index ix_base2_34_days_ago on base2(Thirty4DaysAgo)

Then change your expression to:
and cast(wb1m.[PurchaseDate] as date) >= a.Thirty4DaysAgo

That's what I would recommend before, change the old expression to use the computed column. However, upon further searching, it looks like you can just retain your original code, as SQL Server can intelligently match an expression to the computed column, and if you have an index on that column, your expression would be SARGable. Thus your DBA can optimize things behind the scenes and your original code would run optimized without requiring any changes on your code. So no need to change the following, and it will be SARGable (granted that your DBA created a computed column for dateadd(recurring parameters here) expression, and applied index on it) :
and cast(wb1m.[PurchaseDate] as date) >= DATEADD(dd,-30-4,cast(a.[Week_end] as date))

The only downside (when compared to Postgres) is you still have the dangling computed column on your table when using SQL Server :)
Good read: https://littlekendra.com/2016/03/01/sql-servers-year-function-and-index-performance/

A: You want to have all 90 million base2 rows in your result, each with additional information on base1 data. So, what the DBMS must do is a full table scan on base2 and quickly find related rows in base1.
The query with EXISTS clauses would look something like this:
select
  b2.users_id,
  b2.week_start,
  b2.week_end,
  case when exists
  (
    select *
    from base1 b1
    where b1.users_id = b2.users_id
    and b1.purchasedate between dateadd(day, 7, cast(b2.week_end as date))
                            and dateadd(day, 14, cast(b2.week_end as date))´
  ) then 1 else 0 end as user_will_buy_next_week,
  case when exists
  (
    select *
    from base1 b1
    where b1.users_id = b2.users_id
    and b1.parameter1 = 1
    and b1.purchasedate between dateadd(day, 7, cast(b2.week_end as date))
                            and dateadd(day, 14, cast(b2.week_end as date))´
  ) then 1 else 0 end as user_will_buy_on_condition1,
  case when exists
  (
    select *
    from base1 b1
    where b1.users_id = b2.users_id
    and b1.parameter1 = 1
    and b1.parameter2 = 1
    and b1.purchasedate between dateadd(day, 7, cast(b2.week_end as date))
                            and dateadd(day, 14, cast(b2.week_end as date))´
  ) then 1 else 0 end as user_will_buy_on_condition13,
  case when exists
  (
    select *
    from base1 b1
    where b1.users_id = b2.users_id
    and b1.purchasedate between dateadd(day, -30-4, cast(b2.week_end as date))
                            and dateadd(day, -30+4, cast(b2.week_end as date))´
  ) then 1 else 0 end as was_buy_1_month_ago,
  ...
from base2 b2;

We can easily see that this will take a long time, because all conditions must be checked per base2 row. That is 9 million times 7 lookups. The only thing we can do about this is to provide an index, hoping the query will benefit from it.
create index idx1 on base1 (users_id, purchasedate, parameter1, parameter2);

We can add more indexes, so the DBMS can choose between them on selectivity. Later we can check whether they are used and drop them in case they aren't.
create index idx2 on base1 (users_id, parameter1, purchasedate);
create index idx3 on base1 (users_id, parameter1, parameter2, purchasedate);
create index idx4 on base1 (users_id, parameter2, parameter1, purchasedate);


text:
Q: Store audio in SQL Server? Is it a good idea to store audio files (mp3, wav) in SQL Server as BLOBs? One of the merits appears to be saving Hard disk space. Does this have any impact on scalability or performance?

A: No, it's not a good idea :)  Variable-sized fields (such as TEXT and BLOB) have all sorts of performance impacts.  A better approach is store the files on disk and just maintain a reference to them in a DB table.  Nowadays, hard drive space is so cheap (especially compared to CPU and I/O performance) that it shouldn't even be a concern.

A: I think it depends a lot on how your application is designed.  If you are going to be retrieving the audio files often (or updating them) it could be a serious performance hit as the audio files can be quite large.  Why wouldn't you put them on a shared network location instead and just store the path to the file in the database?  Hard drive space is cheap, bandwidth and SQL performance isn't.  Unless you have a very good reason to keep them in the database (and I don't think saving hard drive space is it) you are better off storing them locally or on a shared path.

A: If you have the option of upgrading to SQL 2008 (i.e. if you're licensed for free upgrades) then FILESTREAM is the best choice - it puts "links" in the column but uses the regular file system to actually store the data.
In SQL 2005 or earlier, I wouldn't do it.  I fail to see how it's going to save hard disk space, either; 5 megs is 5 megs whether it's a file on disk or sitting in a database column somewhere; the latter just makes it harder to get to, and as others have mentioned can have a negative effect on your overall DB performance.  I guess there's some minor file system overhead like minimum cluster sizes, but for large files (especially audio) the effect is negligible.

A: If you are using Sql Server 2008 you can use the filestream attribute. Sql Server will store the file on the file system but link it to a varbinary column.
Check out the link below:
http://www.aghausman.net/sql_server/configure-sql-server-2008-for-file-stream-2.html
(Broken link - still accessible via Internet Archive at https://web.archive.org/web/20120530062012/http://www.aghausman.net/sql_server/configure-sql-server-2008-for-file-stream-2.html)


text:
Q: How to Set EndpointIPAddress in ordering subnet using java How can I set EndpointVlan in verifying Subnet IP.
This is my sample code to verify order. It returns Exceptions with message that Endpoint IP is required.
private void verifyStaticIp() {
    Long packageID = 0l; // ip item only (no sub-option)
    Long quantity = 1l;

    Price price = new Price();
    price.setId(12345l); // sample

    Property property = new Property(); // How to Set enpointVlanId in order template???
    property.setName("endPointVlanId");
    property.setValue("1223445");

    // Create Order to verify
    Order packageOrder = new Order();
    packageOrder.setQuantity(quantity);
    packageOrder.setPackageId(packageID);
    packageOrder.getProperties().add(property);
    packageOrder.getPrices().add(price);

    try {
        Order order = com.softlayer.api.service.product.Order.service(client).verifyOrder(packageOrder);
        System.out.println("verify Static IP order result = " + order.getMessage());
    } catch (Exception e) {
        e.getMessage();
    }
}

A: Please try the following java example:
import com.softlayer.api.ApiClient;
import com.softlayer.api.RestApiClient;
import com.softlayer.api.service.container.product.Order;
import com.softlayer.api.service.container.product.order.network.Subnet;
import com.softlayer.api.service.product.item.Price;

/**
 * Order a new static public Subnet.
 *
 * Important manual pages:
 * http://sldn.softlayer.com/reference/services/SoftLayer_Product_Order/placeOrder/
 * http://sldn.softlayer.com/reference/services/SoftLayer_Product_Order/verifyOrder/
 *
 * @license <http://sldn.softlayer.com/article/License>
 * @author SoftLayer Technologies, Inc. <sldn@softlayer.com>
 */
public class createStaticPublicSubnet {

 /**
  * @param args
  */
 public static void main(String[] args) {

        // Your SoftLayer API username and key.
        String username = "set me";
        String apikey = "set me";

     // Declare item prices
        Long[] prices = { new Long(13983)};

        //The id of the IP address that you want to route a static subnet to.
        Long endPointIpAddressId = new Long(19868866);

        // The number of items to order
        Long quantity = new Long(1);

        String location = "AMSTERDAM";

        // The id of the SoftLayer_Product_Package you want to order.
        Long packageId = new Long(0);

        String containerIdentifier = "SoftLayer_Container_Product_Order_Network_Subnet";

        // Create a SoftLayer API client object
        ApiClient client = new RestApiClient().withCredentials(username, apikey);

        /*
         * Set up Order template
         */
        Subnet newOrder = new Subnet();
        newOrder.setContainerIdentifier(containerIdentifier);
        newOrder.setLocation(location);
        newOrder.setPackageId(packageId);
        newOrder.setQuantity(quantity);
        newOrder.setEndPointIpAddressId(endPointIpAddressId);

        // Add Item prices to list
        for (Long i : prices) {
            Price price = new Price();
            price.setId(new Long(i));
            newOrder.getPrices().add(price);
        }

        try
        {
            Order orderResult = com.softlayer.api.service.product.Order.service(client).verifyOrder(newOrder);
            System.out.println("order successfully verified: " + orderResult);

        } catch (Exception e) {
            System.out.println(e);
        }
 }
}

Update 1.
Also, we can find the "endPointIpAddressId" through virtual Guest id, please see the example:
https://[username]:[apikey]@api.softlayer.com/rest/v3/SoftLayer_Virtual_Guest/[guest_id]/getObject?objectMask=mask[id, fullyQualifiedDomainName,primaryNetworkComponent[id,primaryIpAddress,primaryIpAddressRecord.id]]
Method: GET

The response should be something like this:
{
"fullyQualifiedDomainName": "hostnametest.test.com"
"id": 9054111
"primaryNetworkComponent": {
   "id": 4797111
   "primaryIpAddress": "119.81.111.111"
   "primaryIpAddressRecord": {
      "id": 24692446
  }-
}-

}
Where the value that we need to use to order the subnet is : "id": 24692446
Regards.

A: This is the sample code to get EndPoindIpAddressID I've tried, but it returns nulls only.
private void getEndpointIP(){

    Account.Service accSrv = Account.service(client);

    accSrv.withMask().subnets().endPointIpAddress().id();
    accSrv.withMask().ipAddresses().endpointSubnets().endPointIpAddress().id();
    accSrv.withMask().publicSubnets().endPointIpAddress().id();

    Account acc = accSrv.getObject();

    List<Subnet> subnetList = acc.getPublicSubnets();

    for(Subnet sb  : subnetList){
        System.out.println("EndPoint IP : " + sb.getEndPointIpAddress());
        System.out.println("EndPoint IP ID : " + sb.getEndPointIpAddress().getId());
    }

}

}
This is an alternative way to get EndpointIpAddressId. Please Confirm if this is a valid implementation. Thank you~
private void getEndpointIP_altWay() {

    Account.Service accSrv = Account.service(client);

    accSrv.withMask().subnets().virtualGuests().fullyQualifiedDomainName();
    accSrv.withMask().subnets().virtualGuests().primaryIpAddress().id();
    accSrv.withMask().subnets().virtualGuests().status().name();
    accSrv.withMask().subnets().ipAddresses().ipAddress().id();

    Account acc = accSrv.getObject();

    for (Subnet sub : acc.getSubnets()) {

        List<Subnet> subnetList = acc.getPublicSubnets();

        for (Subnet sb : subnetList) {
            System.out.println("EndPoint IP : " + sb.getEndPointIpAddress());
            System.out.println("EndPoint IP ID : " + sb.getEndPointIpAddress().getId());
        }

        List<IpAddress> ipList = sub.getIpAddresses();

        List<Guest> gList = sub.getVirtualGuests();

        for (Guest gt : gList) {
            System.out.println(" name  : " + gt.getFullyQualifiedDomainName());
            System.out.println(" status  : " + gt.getStatus().getName());
            System.out.println(" public ip  : " + gt.getPrimaryIpAddress());

            for (IpAddress ip : ipList) {

                if (ip.getIpAddress().equals(gt.getPrimaryIpAddress()))
                    System.out.println(" endpoint ip id  : " + ip.getId());

            }

        }

    }

}


text:
Q: join by column type I have 2  tables like the following.
id1 | val | type
1     2     type1
1     4     type2
2     9     type2
2     7     type1

id2|type1|type2
11  2      4
33  7      9

 I need result like this
id1|id2
1   11
2    33

I need to check  both type1 and type2 to relate id1 and id2. I tried the following query but it does not work.
 select id1,id2 from t1 inner join t2 on (type='type1' and
 t1.val=t2.type1)and (type='type2' and t1.val=t2.type2)

A: I believe this should give you what you want:
SELECT
    a.id1,
    t2.id2
FROM
    t2
INNER JOIN
    t1 a ON a.val = t2.type1 AND a.type = 'type1'
INNER JOIN
    t1 b ON b.val = t2.type2 AND b.type = 'type2'
WHERE
    a.id1 = b.id1

A: SQL Fiddle
MS SQL Server 2008 Schema Setup:
CREATE TABLE t1(id1 INT,  val INT,  [type] VARCHAR(10))
INSERT INTO t1 VALUES
(1 ,    2     ,'type1'),
(1 ,    4     ,'type2'),
(2 ,    9     ,'type2'),
(2 ,    7     ,'type1')

CREATE  TABLE t2(id2 INT,  [type1] VARCHAR(10),  [type2] VARCHAR(10))
INSERT INTO t2 VALUES
(11 , 2  ,    4),
(33 , 7  ,    9)

Query 1:
Select t1.id1 , t2.id2
from t1
inner join
(Select * from t2 t
      UNPIVOT (Val for [type]  IN ([type1],[type2]))up) t2
ON t1.val = t2.Val and t1.type = t2.type
GROUP BY t1.id1 , t2.id2

Results:
| id1 | id2 |
|-----|-----|
|   1 |  11 |
|   2 |  33 |


text:
Q: Can i update a part of a text-file? I have build a login-system and i want to count how many times a user has logged in I want to ask to the community how i can update a part of a text-file without overwriting the text-file.
The project i am currently working on is called an login system.
The text-file contains the following values:
- username
- password
- date + time first time registered
- how many times the user has logged in.
But i want to know how i can update a part of a text file, every time a user had logged in i want to track it and write it to the earlier mentioned text-file.

*

*searched google

*stackoverflow

I don't know how to adjust the text-file without overwriting the values it contains.

A: The only way to do this is to actually overwrite the file if you're using text files.
Start by opening the file doing:
with open(file, "r") as read_file:
    string=read_file.read()

Then replace whatever it is you need to in the string, however way you wish to do that, as it is a string at that point.
Then just write it all again by doing:
with open(file, "w") as write_file:
    write_file.write(string)

A: In general, you cannot.  A text file is a sequence of bytes in fixed locations.
You can update only the one record, if you're very careful: make each user's entry a fixed length.  Find it and overwrite only that one short substring of the file.  If the new string is shorter, you will have to pad with blanks or other characters.  If it's longer, your original length estimate is invalid, and you have to omit something.
The application you describe is for some sort of data-base application, in which the file is a collection of records, indirectly addressed.  Also consider using a JSON structure.

For replacing a string of the same length, use the tell and seek methods.
Use tell to recall the position of your string of interest.  Change the value, return to its position with seek, and then write the new string over the original.
I still recommend that you change to a data base representation; overwriting strings is a fragile way to maintain a data store.


text:
Q: Itemize inside algorithm block Lonely \item error \documentclass{article}

\usepackage{algorithm}
\usepackage{algorithmicx}
\usepackage{algpseudocode}%

\begin{document}

\begin{algorithm}
\State \textbf{Inputs:}

\begin{itemize}
    \item Input 1
    \item Input 2
\end{itemize}

\For{each pixel at row, column (x,y)}
    \State Formula 1
    \State Formula 2
    \State Formula 3
    \State Formula 4
\EndFor
\end{algorithm}

\end{document}

I want the text to look exactly like the image here. However, the above latex file gives error "Lonely \item--perhaps a missing list environment". It still compiles and gives the correct output, but the error keeps popping up.
The other answer I found on StackExchange either have no text bullet, or all text bullet.
How can I put itemize inside algorithm like this?

A: algorithm just provide the algorithm float. You need an algorithmic environment to set the algorithm:

\documentclass{article}

\usepackage{algorithm}
\usepackage{algpseudocode}%

\begin{document}

\begin{algorithm}
  \begin{algorithmic}[0]
    \State \textbf{Inputs:}

    \begin{itemize}
      \item Input 1
      \item Input 2
    \end{itemize}

    \For{each pixel at row, column $(x,y)$}
      \State Formula 1
      \State Formula 2
      \State Formula 3
      \State Formula 4
    \EndFor
  \end{algorithmic}
\end{algorithm}

\end{document}


text:
Q: swift - NSPredicate and Context Save is not working well I have a function that checking core data. if doesn't exist it should write to in it(but its not working in that way) SoundItems is an array that contains favorited objects and mainArray is the array that contains real objects;
   @IBAction func Favori(_ sender: Any) {
        // save core data
        let app = UIApplication.shared.delegate as! AppDelegate
        let context = app.persistentContainer.viewContext
        let newSound = NSEntityDescription.entity(forEntityName: "Sounds", in: context)
        let sound = NSManagedObject(entity: newSound!, insertInto: context)
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Sounds")

        let predicate = NSPredicate(format: "soundName = %@", soundArray[soundIndex].deletingPathExtension().lastPathComponent)
        fetchRequest.predicate = predicate
        do {
         let fetchResults = try context.fetch(fetchRequest) as? [Sounds]
              if fetchResults!.count > 0 {

                print("already favd")
            }
         else {

               sound.setValue(soundArray[soundIndex].deletingPathExtension().lastPathComponent, forKey: "soundName")
                    try context.save()
                        soundItems.append(sound)
                            print(sound)

            }
        }

        catch {
        print(error)
        }
    }

and here is the code that listing the core data;
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell
    let sound = soundItems[indexPath.row]
    cell.textLabel?.text = sound.value(forKey: "soundName") as? String

    return cell

}

I tried to run the code in debug mode and it works fine when there is no duplicated core data and adds into the tableView list. But here is the situation; when core data exist(fetchResults!.count > 0) still adding in the tableview as nil label.text but always adds the item of mainArray[0]

A: If you want to check if the sound is in the favorites and if not add a new sound you have to change the order of the steps
@IBAction func Favori(_ sender: Any) {
    // save core data
    let app = UIApplication.shared.delegate as! AppDelegate
    let context = app.persistentContainer.viewContext

    let fetchRequest : NSFetchRequest<Sounds> = Sounds.fetchRequest()
    let favName = soundArray[soundIndex].deletingPathExtension().lastPathComponent
    let predicate = NSPredicate(format: "soundName = %@", favName)
    fetchRequest.predicate = predicate
    do {
        let fetchResults = try context.fetch(fetchRequest)
        if fetchResults.isEmpty {
            let newSound = NSEntityDescription.insertNewObject(forEntityName: "Sounds", into:context) as! Sounds
            newSound.soundName = favName
            try context.save()
            soundItems.append(newSound)
            print(newSound)
        }
        else {
             print("already favd")
        }
    }

    catch {
        print(error)
    }
}

It's recommended to name entities in singular form (Sound).

A: @vadian had the point. Why did you insert a new sound before fetching the data?
 let newSound = NSEntityDescription.entity(forEntityName: "Sounds", in: context)
 let sound = NSManagedObject(entity: newSound!, insertInto: context)


text:
Q: How to get 3D building view in map view in Android? I used the map setting,
googleMap.setBuildingsEnabled(true);

But it's not working.
About a month ago, it was working fine. Attaching the screenshot for ref.
This is the view I was getting a month ago.

Now map shows 2D view.


text:
Q: Magento Cloud Upload changes to master without re-deploy everything? On Magento Cloud, we noticed that each time we upload a code change to the master branch, running something like:
git push magento master

It runs some process and commands, and it takes many minutes. Sometimes it takes five minutes, and another take up to twenty minutes. In that time, the site is not accessible.
In some occasions, the changes we upload are minimal, some image or css change, or one line change of one file.
Someone know if is there some way that we could selectively upload these changes without the site being inaccessible for so long? Maybe omitting any of these processes that are executed, only when we don't see it necessary?
Thanks.

A: Well, I send a ticket to Magento, and they answered me this:

Hello,
What you are seeing is the normal workflow for Magento cloud. For any
  code change, you will need to push and the deployment process will
  take the site down. Here are the articles explaining this:
https://devdocs.magento.com/guides/v2.2/cloud/basic-information/starter-develop-deploy-workflow.html
https://devdocs.magento.com/guides/v2.2/cloud/basic-information/starter-architecture.html
Here is the article that discuss the deployment process, what are the
  5 deployment phases and what scripts run during which phase:
https://devdocs.magento.com/guides/v2.2/cloud/reference/discover-deploy.html
The 5 deployment phases can be summarized into 2: The build phase and
  the deploy phase. During the build phase, your store is being built in
  a container separate from your cloud server so your site is not down.
  It is during the deploy phase where your site goes on maintenance mode
  since this is when the changes are being applied to your site.
  Whatever scripts running in this phase determine how long your site
  will be down for.
The usual script that takes a long time to run in the deploy phase is
  the static content deploy. The length of the deployment is determined
  by how many websites, stores, storeviews, locales, languages you have.
  That's why one way to lessen downtime is to move static content deploy
  from the deploy phase to the build phase so even if it runs for a long
  time, it doesnt affect the downtime of your site (since it's only in
  the deploy phase where your site is placed on maintenance mode).
If you want to try this, please read
  https://devdocs.magento.com/guides/v2.2/cloud/live/sens-data-over.html#cloud-confman-scd-over
Here are other links on static content deployment strategies:
https://devdocs.magento.com/guides/v2.2/config-guide/cli/config-cli-subcommands-static-deploy-strategies.html
https://devdocs.magento.com/guides/v2.2/config-guide/cli/config-cli-subcommands-static-view.html
https://devdocs.magento.com/guides/v2.2/cloud/env/variables-deploy.html#scd_compression_level

So, as I understand, it is normal and no, is no way to do it without that.


text:
Q: jQuery: handle click on submit button I try to handle a click on a submit button but it doesn't seem to work, as if my selector was wrong but I really can't tell what my mistake is.
Basically it's just the following:
$(".edit input").click(function() {
    $(".note").html($(this).val());
    $(".edit").html(editHTML);
});

Here is my test on jsfiddle:
http://jsfiddle.net/D7Teb/

A: You need to delegate the events since you are adding some of the content after you run the initial listener code.  The below works with jQuery 1.7+ as it utilises the on method.  If you have to use an earlier version look inot the delegate() method.
http://learn.jquery.com/events/event-delegation/
http://api.jquery.com/on/
http://api.jquery.com/delegate/
Demo: http://jsfiddle.net/robschmuecker/D7Teb/1/
var noteHTML = $(".note").html();
var editHTML = $(".edit").html();
var noteAltHTML = '<input class="myInput" type="text" />';
var editAltHTML = '<button>Save</button>';

$(document).on('click', ".edit a", function () {
    $(".note").html(noteAltHTML);
    $(".edit").html(editAltHTML);
});

// Since you are adding the HTML after the initial running and adding of the listeners, you have to 'delegate' the event like this with
$(document).on('click', ".edit button", function () {
    $(".note").html($(".myInput").val());
    $(".edit").html(editHTML);
});


text:
Q: SWT StyledText Widget - WhiteSpace Painting I have a StyledText widget in an SWT app with formatted text like so:
Type                 -> Text
MessageID            -> ID:205871803-172.30.227.122(89:ab:da:58:b9:f3)-32849-1332173293715
CorrelationIDAsBytes -> [B@d1c778
Expiration           -> 0
Priority             -> 4
Timestamp            -> 1332173293715
Redelivered          -> false

However, this is what it ends up looking like:

Is there some option I can turn on to make it display the whitespace "as is"?
I tried adding some style to it to get it to look right, but it still doesn't work:
        _messageDataText.addLineStyleListener( new LineStyleListener() {
            public void lineGetStyle( final LineStyleEvent lineStyleEvent ) {
                StyleRange styleRange = new StyleRange();
                styleRange.start = 0;
                styleRange.length = _messageDataText.getText().length();
                styleRange.font = new Font( Display.getCurrent(), "Arial", 12, SWT.NORMAL );
                lineStyleEvent.styles = new StyleRange[] {
                    styleRange };
            }
        } );

A: Apparently it depends on the font. If you use "Courier New" instead the whitespace lines up properly.
This is what I changed:
styleRange.font = new Font( Display.getCurrent(), "Courier New", 10, SWT.NORMAL );
Also, as a side note - it is important to reuse fonts wherever possible or you'll get nasty handle problems.


text:
Q: Parsing CSV file rows for SpreadSheets upload with AJAX I'm trying to send leads from CSV to Google Sheets with AJAX like
this method
for send form leads to Google Sheets.
I got it with this code in Gogole App Script but i need this in local to do more actions as delete csv file on finish.
function importCSVFromWeb() {

  var csvUrl = "http://URL/csv/data.csv";
  var csvContent = UrlFetchApp.fetch(csvUrl).getContentText();
  var csvData = Utilities.parseCsv(csvContent);
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getDataRange();
  var lastRow = range.getLastRow();

  sheet.getRange(lastRow + 1, 1, csvData.length, csvData[0].length).setValues(csvData);
}

This is an example of my data.csv
"4","7","22300","johndoe@example.com","John","Doe","Company SL","666123456","519780151","","","","Instagram"
"6","10","08028","johnsmith@example.com","John","Smith","Company2 SL","666456789","519780151","","","","Facebook"

And this is my AJAX script:
  <script>
    $.ajaxSetup({ cache: false });//disable cache

    $.ajax({
        url: 'csv/data.csv',
        dataType: 'text',
      }).done(successFunction);

    function successFunction(data) {
      var allRows = data.split(/\r?\n|\r/);
      for (var singleRow = 0; singleRow < allRows.length; singleRow++) {

      var rowCells = allRows[singleRow].split(',');
        document.querySelector("#leads-csv").innerHTML += rowCells+"<br/>";

        //alert(rowCells);

        const sheetsURL = 'https://script.google.com/macros/s/XXXXXXXXXXXXXXXXXXXXX/exec'
      const sheets = document.forms['form-csv'] //evento de formulario

            sheets.addEventListener('submit', e => {
                e.preventDefault()

                alert("Se va a insertar en Google Sheets");//once by row

                fetch(sheetsURL, {
                        method: 'POST',
                        body: new FormData(sheets) //Failed to construct FormData!!
                    })
                    .then(response => console.log('Datos guardados en Google Sheets', response))
                    .catch(error => console.error('¡Error, revisa el código superior!', error.message))
            });
      }
    }
    </script>

I have the problem when i trying to create the FormData with CSV rows

A: Finally I used Guzzle PHP, submitting async forms is much easier than cheating with javascript. Here the little snippet of victory:
    $file = fopen("csv/datos.csv", "r");

    if($file) {

    //If file exists, start read
    while(! feof($file)) {
    $line = fgets($file);

    //Convert complete line to single fields
    $singleLine = explode(",",$line);

        $client = new \GuzzleHttp\Client();

        //CSV fields to Google Sheets fields
        $response = $client->request('POST', 'https://script.google.com/macros/s/URL/exec', [
                'form_params' => [
                'nombreDeVariable2' => $singleLine[0],
                'nombreDeVariable3' => $singleLine[1],
                'Zip' => $singleLine[2],
                'email' => $singleLine[3],
                'first_name' => $singleLine[4],
                'last_name' => $singleLine[5],
                'company' => $singleLine[6],
                'phone' => $singleLine[7],
                'elqSiteId' => $singleLine[8],
                'comentarios' => $singleLine[9],
                'gdpr_legitimate_interest' => $singleLine[10],
                'retURL' => $singleLine[11],
                'web' => $singleLine[12],
            ]
        ]);

For post to JSON API y only changed "form_params" for "json", adding API end point and this lines after:
$response = $client->post("/end-point", $options);
echo $response->getBody();


text:
Q: ORACLE update with returning OLD and NEW values Is there equivalent to this T-SQL query in PL/SQL (Oracle 12c)?
UPDATE A SET A.columnA = 10 WHERE A.columnB < 30 OUTPUT INSERTED.*, DELETED.*
The query updates table A and at the same time returns the status of the record before the update and after the update.
Trigger is not a solution for me as well as SELECT records before and SELECT records after updating.

A: Not a direct one, but using RETURNING INTO you will be able to achieve the same effect:
CREATE TABLE A(columnA VARCHAR2(10), columnB INT);
INSERT INTO A(columnA, columnB) VALUES ('Test', 10);
INSERT INTO A(columnA, columnB) VALUES ('Row 2', 20);
CREATE TABLE audit_table(col_new VARCHAR2(10),col_old VARCHAR2(10));

DECLARE
   TYPE rec IS RECORD (actual A.columnA%TYPE, old A.columnA%TYPE);
   TYPE col_a_t IS TABLE OF rec;
   v_a col_a_t;
BEGIN
  UPDATE (SELECT A.*, (SELECT A.columnA FROM dual) AS old_columnA FROM A)
  SET columnA = 'XYZ'
  WHERE columnB < 30
  RETURNING columnA, old_columnA BULK COLLECT INTO v_a;
  COMMIT;

  -- printing for debug
  FOR i IN v_a.first .. v_a.last LOOP
     dbms_output.put_line('Old =>' || v_a(i).old || ' new => ' || v_a(i).actual);
  END LOOP;

  -- additional
  FORALL i IN v_a.first .. v_a.last
    INSERT INTO audit_table VALUES v_a(i);
  COMMIT;
END;
/

SELECT * FROM A;
SELECT * FROM audit_table;

DBFiddle Demo

Idea taken from: Returning Old value during update


text:
Q: Memory Leak in my PHP App (built with Codeigniter Framework) I have a PHP app built on Codeigniter 1.7.2, currently in production and live, that seems to have a serious memory leak.
The memory leak is apparent from looking at "top" on the server:
top - 23:42:13 up 26 days, 10:14,  1 user,  load average: 0.00, 0.00, 0.00
Tasks:  54 total,   1 running,  53 sleeping,   0 stopped,   0 zombie
Cpu(s):  0.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st Mem:   7872040k total,   929748k used,  6942292k free,   142464k buffers
Swap:        0k total,        0k used,        0k free,   214420k cached
PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
22740 apache    15   0  308m  63m 5976 S    0  0.8   0:14.05 httpd

22733 apache    15   0  298m  54m 5968 S    0  0.7   0:13.60 httpd

22736 apache    15   0  296m  52m 5968 S    0  0.7   0:13.89 httpd

22742 apache    15   0  295m  50m 5976 S    0  0.7   0:13.05 httpd

22738 apache    15   0  294m  49m 5968 S    0  0.6   0:13.30 httpd

22744 apache    15   0  293m  48m 5968 S    0  0.6   0:13.11 httpd

So httpd is using 0.8% * 7.9GB of memory or approx 63MB.
I know CI plus my app has a footprint of about 7MB. I know httpd probably has some but can't explain 63MB, plus this number goes up daily if I reboot. Thus I concluded there was a memory leak.
From my understanding of PHP 5.2.x, it doesn't quite do "garbage collection" but will free memory upon function exit and finally on script termination. Also, I know of a few known constructs that can result in a memory leak ("child object destruction", and recursive object references), but I'm not doing anything that fancy. So I'm a bit stumped what the problem could be.
I'm going to try to track it down using XDebug but I'm having some issues installing it on Fedora 8. If anyone can point out some "usual suspects" for true memory leaks in PHP 5.2.x, and/or in Code Igniter...I'm hoping I can get lucky and just find the culprit if I know what to look for (I've googled for known issues in CI but no smoking guns. I did turn off a feature that persisted queries between functions and that helped reduce the footprint but it still seems to be leaking).
[root@web7 ~]# php --version
PHP 5.2.6 (cli) (built: May  8 2008 08:54:23)
    Copyright (c) 1997-2008 The PHP Group
    Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies

[root@web7 ~]# cat /proc/version
    Linux version 2.6.21.7-2.fc8xen (mockbuild@xenbuilder4.fedora.phx.redhat.com) (gcc version 4.1.2 20070925 (Red Hat 4.1.2-33)) #1 SMP Fri Feb 15 12:34:28 EST 2008

A: Have you tried turning profiling on in your controller:
$this->output->enable_profiler(TRUE);

Would be interesting to see if anything crops up in the results of that which shows something is taking a little longer than usual.
Additionally you can always try CodeIgniter 2 which has now been released, the upgrade is backward compatible and has a lot of fixes.
--edit
You could also try this:
I found an variable "var $save_queries = TRUE;" on line 51 in file /system/database/DB_driver.php
Switching this to FALSE solved the issue for me.
From your controller you can use: $this->db->save_queries = FALSE; Where the leak should be an issue.
--edit


text:
Q: Nginx: rename URL after a redirection My new website's address is foo.pro, when I go my old website bar.pro, it shows the content of the new foo.pro as expected but the URL remains bar.pro.
How to replace bar.pro by foo.pro in my Nginx configuration below ?
upstream foo_upstream {
    server 127.0.0.1:3003;
    keepalive 64;
}

server {

    server_name www.foo.pro;

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header Host $http_host;

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        proxy_pass http://foo_upstream;
        proxy_redirect off;
        proxy_read_timeout 240s;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/www.foo.pro/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/www.foo.pro/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

server {
    if ($host = www.foo.pro) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80;

    server_name www.foo.pro;
    return 404; # managed by Certbot

}

server {
    listen       80;
    server_name  foo.pro;
    return 301 https://www.foo.pro;
}

=== EDIT ===
I tried to add this directive in my conf:
server {
    listen       80;
    server_name  bar.pro;
    return 301 https://foo.pro;
}

But it's still not renaming the URL to foo.pro.


text:
Q: How to set location triggers dynamically in Worklight? I need to create new geofence circles dynamically for each location I get from a Worklight Adapter. I need to do it using a loop, as I dunno how many locations are defined in backend service. Furthermore a new location can be define meanwhile the application is running.
I have seen several samples for an established set of locations but I dunno how to get it working in my scenario...

A: I have already found a solution. This is the code in case someone needs it:
var triggers = new Object();
triggers.Geo={};
triggers.Geo.Cliente = {
    type: "Enter",
    circle: {
      longitude: xxxxxx,
      latitude: xxxxxxx,
      radius: proximidad // 300m
    },
    confidenceLevel: "high", // ~95% confidence that we are in the circle
    eventToTransmit: {
      event: {
        name: 'clientecerca'
      },
      transmitImmediately: true
    }
  };

A: Generating Triggers using an external function:
var triggers = new Object();
triggers.Geo={};
triggers.Geo.Cliente = generaTriggers("41.43373","-3.80052");

function generaTriggers(lat,lon){

    var Cliente ={
        type: "Enter",
        circle: {
          longitude: lon,
          latitude: lat,
          radius: proximidad // 300m
        },
        confidenceLevel: "high", // ~95% confidence that we are in the circle
        eventToTransmit: {
          event: {
            name: 'clientecerca'
          },
          transmitImmediately: true
        }
      };
    return Cliente;
}

A: This is the final result for adding dynamically location triggers:
*Note: vector is a javascript array that contains the latitude and longitude of the different geofences circles*
function Geofencing(){

var policy = { Geo: WL.Device.Geo.Profiles.LiveTracking() };
var triggers = new Object();
triggers.Geo={};

var triggersgenerados = generaTriggers();

triggers.Geo = triggersgenerados;

WL.Device.startAcquisition(policy, triggers, geoFailure);
WL.App.setKeepAliveInBackground(true);
}
function generaTriggers(){
    var triggersvisitas= new Object;
    for(var i=0; i< vector.length;i++){
        var Cliente ={
                type: "Enter",
                circle: {
                  longitude: vector[i].longitud,
                  latitude: vector[i].latitud,
                  radius: proximidad // 300m
                },
                confidenceLevel: "high",

                eventToTransmit: {
                  event: {
                    name: 'clientecerca'
                  },
                  transmitImmediately: true
                }
              };
        triggersvisitas["Cliente"+i]=Cliente;
    }

    return triggersvisitas;
}


text:
Q: Android: INSTALL_FAILED_DEXOPT while install app on android 1.5 I am developing app which bust run on both Android 1.5 and Andoroid 2.x platforms.
When I install it on Android 2.2 all is OK, but on emulator with Android 1.5 I get an error:
Failure [INSTALL_FAILED_DEXOPT]

What is the problem may be?
UPD That is Logcat output:
09-26 07:12:22.484: INFO/PackageManager(579): /data/app/vmdl23706.tmp changed; unpacking
09-26 07:12:22.494: DEBUG/installd(557): DexInv: --- BEGIN '/data/app/vmdl23706.tmp' ---
09-26 07:12:36.114: ERROR/dalvikvm(1362): LinearAlloc exceeded capacity, last=336
09-26 07:12:36.114: ERROR/dalvikvm(1362): VM aborting
09-26 07:12:36.265: INFO/DEBUG(551): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
09-26 07:12:36.265: INFO/DEBUG(551): Build fingerprint: 'generic/sdk/generic/:1.5/CUPCAKE/150240:eng/test-keys'
09-26 07:12:36.265: INFO/DEBUG(551): pid: 1362, tid: 1362  >>> /system/bin/dexopt <<<
09-26 07:12:36.265: INFO/DEBUG(551): signal 11 (SIGSEGV), fault addr deadd00d

It seems that memory was not enough... If anybody knows how to fight with such problem? I would be very grateful for any help.

A: It's a limitation in Dalvik triggered on unusually complex interface hierarchies.
http://code.google.com/p/android/issues/detail?id=22586
See the details for ideas on working around. Simple answer might be to try using different libraries that are less complex.
A fix has been merged into Android AOSP.
https://android-review.googlesource.com/#/c/30900/

A: I had this issue when trying to install my app on the emulator. What helped was to reset the emulator (wipe all user data) via AVD Manager. Let's see how long this will last....


text:
Q: Python Unexpected keyword argument' in constructor call Hi and thanks in advance for your help.  I am not a Python expert but an accomplished programmer in other languages.
I'm getting the error on "is_server_running"
Client
from ibw.client import IBClient

REGULAR_USERNAME = 'MY_ACCOUNT_USERNAME'
REGULAR_ACCOUNT = 'MY_ACCOUNT_NUMBER'

# Create a new session of the IB Web API.
ib_client = IBClient(username=REGULAR_USERNAME,
                     account=REGULAR_ACCOUNT,
                     client_gateway_path=None,
                     is_server_running=True)

class IBClient():

    def __init__(self, username: str, account: str, client_gateway_path: str = None, is_server_running:
                 bool = True) -> None

        self.account = account
        self.username = username
        self.client_gateway_path = client_gateway_path
        self.client_portal_client = ClientPortal()

        self.api_version = 'v1/'
        self._operating_system = sys.platform
        self.session_state_path: pathlib.Path =
                                 pathlib.Path(__file__).parent.joinpath('server_session.json').resolve()
        self.authenticated = False
        self._is_server_running = is_server_running

        # Define URL Components
        ib_gateway_host = r"https://localhost"
        ib_gateway_port = r"5000"
        self.ib_gateway_path = ib_gateway_host + ":" + ib_gateway_port
        self.backup_gateway_path = r"https://cdcdyn.interactivebrokers.com/portal.proxy"
        self.login_gateway_path = self.ib_gateway_path + "/sso/Login?forwardTo=22&RL=1&ip2loc=on"

[more code]

Again thanks in advance for your help

Bob


text:
Q: How to search Bookmark with ctrlp in VIM With command CtrlPBookmarkDirAdd which is added sucessfully a bookmark. But I couldn't find any instruction how to list the added bookmarks like NERDTree.
Any method ? Thanks

A: :CtrlPBookmarkDir is very close to :CtrlPBookmarkDirAdd in :h ctrlp.

A: I had trouble that :CtrlPBookmarkDir<CR> shows == NO ENTRIES ==, although :CtrlPBookmarkDirAdd <Dir> finished successfully.
In my case, this was caused by permission about $HOME./.cache/ctrlp.
It was made with root owner.
Maybe, I used CtrlP plugin with sudo vim at first time.
I fixed direcotry owner and register bookmarks again, then I got proper output.


text:
Q: Install SSL Certificate with BlackBerry App We have a BlackBerry app that access a secure web service that uses a SSL Certificate that is not installed on some BlackBerry OS5 devices. This is causing problems for users of our apps who see this message.
"You are attempting to open a secure connection, but the server's certificate is not trusted."
We can install the cert manually by this method
https://search.thawte.com/support/ssl-digital-certificates/index?page=content&id=SO4477&actp=search&viewlocale=en_US&searchid=1328216150785
but this is obviously not a good solution for our customers.
Is there a way to package & install the required cert with the app? This cert works fine with iOS, Android, IE, Firefox & Chrome.

A: You can include the cert X509 in the code bundle as a resource and put it in the key store. But the user will have to manually go into their certificate store and trust it. If the user has not previously used the certificate store this will have the unfortunate side effect of forcing them to pick a password at that point.
The following code will read a certificate from a resource file in PEM format but with the -----BEGIN/END CERTIFICATE----- lines removed. I have used all the elements of this code, but not in this exact configuration. If there are any problems with it I would be happy to try to sort them out.
The certificate won't be trusted so the user will have to manually go into the certificate store application under device Options and "Trust" the certificate. Make sure they understand that they can not revoke the certfificate. That operation can not be undone on the device without wiping and re-installing the OS. The only other option is to re-issue a new certificate.
If anyone knows how to get arround these finiky bits let me know and I will include the solution in this code, or link to wherever it exists now.
X509Certificate _x509;

try {
    // Get an input stream for the certificate in a resource file
    InputStream rs = getClass().getResourceAsStream("/certificate.pem");

    // PEM format is Base64 encoded
    Base64InputStream b64is = new Base64InputStream(rs);

    // Create the X509 certificate
    _x509 = new X509Certificate(b64is);

    // Clean up.
    b64is.close();
    rs.close();

    // if the certificate is self signed this will perform a
    // verfication check. For non-self signed certificates
    // one could provide the signer's certificate in another
    // resource file and validate it with that public key. Other
    // versions of verify will verify it with a certificate in
    // a keystore, but then we wouldn't need to do all this.
    _x509.verify(_x509.getPublicKey());
    System.out.println(_x509.getSubjectFriendlyName());
    System.out.println(Integer.toHexString(_x509.hashCode()));

    // Add the certificate to the DeviceKeyStore
    KeyStore ks = DeviceKeyStore.getInstance();

    // Associated data is set to null, but can be used if there is associated
    // data known. You can use _x509.getStatus() instead of encoding the GOOD
    // constant, but if the device can not find a revokation or validation list
    // it will set the status to UNKNOWN which will confuse users. ks.getTicket()
    // will prompt the user for permission for the program to access the key store.
    // This may also cause the system to ask the user to set a password, unfortunately
    // I can't remember, but I don't think it will if there is no private key in the
    // certificate.
    ks.set(null, _x509.getSubjectFriendlyName(), _x509, CertificateStatus.GOOD,
       ks.getTicket() );
} catch (CertificateException ce) {
    System.out.println(ce.toString());
} catch (CryptoException crypt) {
    System.out.println(crypt);
} catch (IOException ioe) {
    System.out.println(ioe.toString());
}


text:
Q: How to copy files from the linux to windows with rcp I want to remote copy the file from linux to windows with rcp. While the rcp cmd don't support the "c:". How can I rcp to the c:\
rcp /home/CommonFuncs.pm windows2003:C:/CommonFuncs.pm
Winsock RSHD/NT: Error 3 executing '/usr/lib/sunw,rcp -tZ C:/CommonFuncs.pm' The system cannot find the path specified.

rcp /home/CommonFuncs.pm windows2003:C:/CommonFuncs.pm
Winsock RSHD/NT: Error 3 executing '/usr/lib/sunw,rcp -tZ C\:/CommonFuncs.pm' The system cannot find the path specified.

A: Rather try using scp command like below
scp /home/CommonFuncs.pm user@hostname:C:\CommonFuncs.pm