text:
Q: Left join condition on right Using Linq and EF
One User can have many RoleUserLinks.
If a User's RoleUserLink table contains 2 records - one which has a LinkStatusID of Deleted and one which has a LinkStatusID of Added, the query below returns the User.  I don't want this.
How to not return the user if there are any associated LinkStatusID's of Added see case 3 below
IEnumerable<User> z =
    (from users in listOfUsersForReviewer
     join roleUserLinks in context.RoleUserLinks
        on users.UserID equals roleUserLinks.UserID into roleUserLinksJoin
     // left join
     from roleUserLinks in roleUserLinksJoin.DefaultIfEmpty()
     where
         // case 1 - has never been added to a role ie record isn't there
         roleUserLinks.LinkStatus == null
         // case 2 - has been soft deleted from a role so we want this record
         || roleUserLinks.LinkStatusID == (byte)Enums.LinkStatus.Deleted
     select users).Distinct();

case 1) User has no associated RoleUserLink records.  user is returned as expected
case 2) User has 1 associated RoleUserLink record with LinkStatusID of Deleted. user is returned as expected
case 3) User has 2 associated RoleUserLink records.  1 has a LinkStatusID of Deleted.  user should not be returned

A: If I understand it well it should be:
IEnumerable<User> z =
    (from users in listOfUsersForReviewer
     join roleUserLinks in context.RoleUserLinks
        on users.UserID equals roleUserLinks.UserID into roleUserLinksJoin
     // left join
     from roleUserLinks in roleUserLinksJoin.DefaultIfEmpty()
     where
         (roleUserLinks == null
         || roleUserLinks.LinkStatusID == (byte)Enums.LinkStatus.Deleted)
         && !roleUserLinksJoin.Where(x=> roleUserLinks.LinkStatusID == (byte)Enums.LinkStatus.Added && x.UserID == roleUserLinks.UserID).Any()
     select users).Distinct();

I have added this subquery:
&& !roleUserLinksJoin.Where(x=> roleUserLinks.LinkStatusID == (byte)Enums.LinkStatus.Added && x.UserID == roleUserLinks.UserID).Any()

It will remove unwanted rows from result with users which has record in RoleUserLinks with LinkStatusId Added.
I have also changed this roleUserLinks.LinkStatus == null to roleUserLinks == null to avoid NullReferenceException in case there will be no matching RoleUserLink for User
Sample code on which I tested my code
static void Main(string[] args)
{
    var usersList = new List<User>()
                    {
                        new User() {UserID = 1},
                        new User() {UserID = 2},
                        new User() {UserID = 3}
                    };

    var userLinksList = new List<RoleUserLink>()
                        {
                            new RoleUserLink() {UserID = 1, State = "del"},
                            new RoleUserLink() {UserID = 2, State = "add"},
                            new RoleUserLink() {UserID = 2, State = "del"}
                        };

    IEnumerable<User> z = (from users in usersList
                           join roleUserLinks in userLinksList
                           on users.UserID equals roleUserLinks.UserID into roleUserLinksJoin
                           // left join
                           from roleUserLinks in roleUserLinksJoin.DefaultIfEmpty()
                           where
                            // has never been added to a role ie record isn't there
                                roleUserLinks == null
                            // has been soft deleted from a role so we want this record
                                || roleUserLinks.State == "del"
                            // has been added to role so we don't want this record
                                && !roleUserLinksJoin.Where(x=> x.State == "add" && x.UserID == roleUserLinks.UserID).Any()
                            select users).Distinct();
    var res = z.ToList();

}

public class User
{
    public int UserID { get; set; }
}

public class RoleUserLink
{
    public int UserID { get; set; }
    public string State { get; set; }
}

It returns user with id 1 and 3. As I expected. UserId:1 has only link with status delete. UserId:3 does not have any link. And UserId:2 is not returned because it has also link with status add.

A: I solved this problem by taking the original query:
IEnumerable<User> z =
    (from users in listOfUsersForReviewer
     join roleUserLinks in context.RoleUserLinks
        on users.UserID equals roleUserLinks.UserID into roleUserLinksJoin
     // left join
     from roleUserLinks in roleUserLinksJoin.DefaultIfEmpty()
     where
         // case 1 - has never been added to a role ie record isn't there
         roleUserLinks.LinkStatus == null
         // case 2 - has been soft deleted from a role so we want this record
         || roleUserLinks.LinkStatusID == (byte)Enums.LinkStatus.Deleted
     select users).Distinct().Include(b => b.RoleUserLinks).ToList();

and added the Include and ToList at the end.
Then:
var list = new List<User>();

    foreach (var user in z)
    {
        bool shouldReturnUser = true;
        //get roleLinks
        foreach (var rul in user.RoleUserLinks)
        {
            if (rul.LinkStatusID == (byte) Enums.LinkStatus.Added)
                shouldReturnUser = false;
        }
        if (shouldReturnUser)
            list.Add(user);
    }

then returning this list.
I understand there is a perf hit by doing this, and processing on the webserver, but IMHO this is very easy to understand, and it works :-)


text:
Q: How to open numeric keypad for html password field in IOS/ANDROID I want to open numeric keyboard for android/ios hybrid app. I have tried below code but it isn't working -
   <input type="password"
   pattern="[0-9]*"
   inputMode="numeric" />

redpajama_set_name: RedPajamaStackExchange


text:
Q: apache htaccess - trailing slash and single entry point I need to have one entry point for my application - index.php.
Before, i used to have such line of code:
RewriteRule ^(.*)$ /index.php [L]
Now, i need to force trailing slashes. I found out, that I can use such line:
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1/ [L,R=301]
But I want to know, how can I make it work both together.

A: try something like
RewriteRule ^(.*)$ /index.php/$1 [L]

or
RewriteRule ^(.*)$ http://%{HTTP_HOST}/index.php/$1/ [L]


text:
Q: Predefine column data type in Excel Sheet Is there any way in which I can predefine data type of a column of an excel sheet ?
For eg. when I enter 0022598741 in a column it will be formatted as 22598741 but I want it as it is.In this case this particular column takes the data as number type but I want it to be taken as text type.

A: Format it as Text before input: right click > cell properties.


text:
Q: Do I have mistakes in my calculations (power series, convergence)? I'm not sure I got all of these problems right. I'd really appreciate any sort of feedback.
For which $x \in \mathbb{R}$ do the following series converge?
Problem 1
For $\sum\limits_{n=1}^{\infty}\frac{3n^7x^n}{2n!} = \sum\limits_{n=1}^{\infty}\frac{3n^7}{2n!}x^n$, perform a ratio test: $$\lim\limits_{n\to \infty}\left|\frac{3(n+1)^7}{2(n+1)!} \cdot\frac{2n!}{3n^7}\right| = \lim\limits_{n\to \infty}\left|\frac{(n+1)^7}{(n+1) \cdot n^7}\right|= \lim\limits_{n\to \infty} \left|\frac{(n+1)^6}{n^7}\right|\\= \lim\limits_{n\to \infty}\left|\frac{n^6+6n^5+15n^4+20n^3+15n^2+6n+1}{n^7}\right| = \lim\limits_{n\to \infty} 0 =0$$
$\implies$ The ratio of convergence is therefore $r = \infty$.
$\implies$ The power series absolutely converges for any $x \in\mathbb{R}$.
$$\\$$
Problem 2
For $\sum\limits_{n=1}^{\infty}\frac{(x-1)^n}{n}$, we see that the coefficients $a_n$ are formed by the harmonic series $a_n = \frac{1}{n}$.
Note that $\lim\limits_{n \to \infty} a_n = 0$.
$\implies$ The ratio of convergence is therefore $r = \infty$.
$\implies$ The power series absolutely converges for any $x \in\mathbb{R}$.
$$\\$$
Problem 3
For, $\sum\limits_{n=1}^{\infty}\frac{(-4nx)^n}{2n^3} = \sum\limits_{n=1}^{\infty}\frac{(-4n)^n}{2n^3}x^n$ , perform a root test: $$\lim\limits_{n\to \infty}\left|\sqrt[n]{\frac{(-4n)^n}{2n^3}}\right| = \lim\limits_{n\to \infty}\left|\frac{-4n}{\sqrt[n]{2n^3}}\right|=
\lim\limits_{n\to \infty}\left|\frac{-4n}{\sqrt[n]{2}\sqrt[n]{n}\sqrt[n]{n}\sqrt[n]{n}}\right| = \infty, \text{ since} \lim\limits_{n\to\infty} \sqrt[n]{n}=1$$.
$\implies$ The radius of convergence is $r = \infty$.
$\implies$ The power series will only converge for $x = 0$.

A: If x=2 in number 2, does the series converge?


text:
Q: riptscope of a variable in jQuery I have following AJAX.
And what I need to do is to use the variable tax_rate outside of $.ajax call. My ajax call is working properly since the variable tax_rate shows proper value in [1], but the variable becomes useless in [2].
Am I doing something wrong with variable scope?
<script>
jQuery(document).ready(function($) {

    $(document).on('blur','#form',function() {

        var subsum = 0;
        var tax_rate = 0;
        var tax_amount = 0;

        $('.form-row').each(function() {

            // calculate sums and totals per each form-row
            subsum = Number( $(this).find('.unit').val() * $(this).find('.price').val() ).toFixed(2);
            $(this).find('.subsum').empty().val(subsum);

            // calculate tax amount
            var tax_id= $(this).find('.tax_code').val();
            var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';

            // call ajax to retrieve the tax rate
            $.ajax({
                url: ajaxurl,
                data:' action=get_tax_rate_by_id&tax_id='+tax_id,
                type:'GET',
                success:function(results) {
                    tax_rate = results;
                    alert( tax_rate ); // [1] Obviously, this one properly alerts tax rate.
                }
            });

            alert( tax_rate ); // [2] This one always alerts 0.

        });

    });
});

A: You have to make your ajax call synchronously because the alert will get executed before completing your ajax request as JavaScript run asynchronously. Although it will make your code a little slow but you will be able to return tax_rate outside of ajax. You can use
async:false

in your ajax options to do that.

A: What if you try:
            success:function(results) {
                return tax_rate = results;
            }


text:
Q: Using Terraform to copy website files/folders from GitHub repo to AWS S3 I'm trying to figure out a way to copy all files/folders from a GitHub repro to an AWS S3 bucket using Terraform.
I came across the github_repository_file data source, but I believe it is limited to a single file vs multiple files and directories.
Thank you in advance!


text:
Q: Integral of $\int \frac{1}{x^2(x^4+1)^{3/2}}dx$ How to find
$$\int \frac{1}{x^2(x^4+1)^{3/2}}dx$$
I tried taking $x^4$ common but that generated $x^8$ outside which made things complicated. Putting $x^4+1=t^2$ also didn't solve the query. Can someone hint something?


text:
Q: Load specific elements from a page with an AJAX call and append them to a list? I've got two page:
Page 1 has a title, an empty ol and some jQuery that calls an AJAX function.
Page 2 has an ol filled with list items from which I plan on pulling specific ones.
The AJAX I'm using looks as follows:
$("#loader").load("ajax.html li:nth-child(1)");

It works great in pulling in that first li. However, if something is already in #loader it is replaced. Instead, I'd like it to append the new li behind the already existing ones. I've tried using the ajax() function but that does not allow you to call forth a specific element the way the load() function does, or, at least, I can't find a way.
What I'm eventually going to do is make it so that a series of li's are called in via an AJAX call and added to the already-existing list. The problem is I'm getting stuck on the initial adding. The rest I'm pretty sure I can figure out by calling a function that contains a for-loop.

A: using $get instead of $.ajax
var loadContent = function(url, targetSelector, contentSelector){
   var target = $(targetSelector);
   $.get(url, function(data){
     target.append($(targetSelector, data));
   });
};

loadContent('ajax.html', '#loader', 'li:nth-child(1)');

You could of course skip the function definition and just do it all with the callback to $.get:
$.get('ajax.html', function(data){
   $('#loader').append($('li:nth-child(1)',data));
});

If you just want the html content of the li or ol then use $('li:nth-child(1)',data).html() in the append calls instead.


text:
Q: same or similar search word with field calculator I am using arcgis 10.1
I have two tables A and B need to find attributes of table B data are on the table A
I'm doing a join between table A and B now I want to use the field calculator via a script  to compare field "name" field of table A and table name B
I need help on how to make this script

A: If you are checking for duplicate row values between fields, an UpdateCursor is what you want.  Attached is a simple script to accomplish this goal.  The assumptions here are that you have three fields: FIELD1 (row[0]) and FIELD2 (row[1]) are being compared and the results are recorded in FIELD3 (row[2]), where "1" = duplicate and "0" = unique.
import arcpy

fc = r'C:\path\to\your\fc'

with arcpy.da.UpdateCursor(fc, ["FIELD1", "FIELD2", "FIELD3"]) as cursor:
    for row in cursor:
        if row[0] == row[1]:
            row[2] = 1
        else:
            row[2] = 0
        cursor.updateRow(row)


text:
Q: Image Smoothing Using Median Filter I am working on image smoothing using median filter. For that, I am not using the inbuilt functions within the Python library, rather I am writing my own functions. The following code is for calculating the median.
def CalcMedian(Image, x, y, gridSize):    #x and y are nested loops, that run over the entire image.
    medianList = []
    row, col = Image.shape;
    k = int(gridSize/2);
    for i in range(gridSize-1):
        for j in range(gridSize-1):
            if (i+x-k)<0 or (j+y-k)<0 or (i+x-k)>row or (j+y-k)>col:
                break;
            medianList.append(Image[(i+x-k),(j+y-k)]);
    medianList.sort();
    length = len(medianList);
    if length%2 != 0:
        return float(medianList[length/2]);
    return float((medianList[int((length-1)/2)] + medianList[int(length/2)]) / 2.0);

I am getting an  error in the last line.

IndexError: list index out of range

I can't figure out as to what the problem is, as this is a standard code used for finding the median, and I don't understand where exactly the index would be out of range.

A: I used you function and some dummy data to test and it works. I get the index out of bounds error only when the value of x or y is equal to row or col respectively.
check, on what value of x and y you get that error.


text:
Q: css issue while downloading png image from svg in nvd3 I have one line chart using nvd3.js . I want to download this chart in .png format.
I am using canvas and sending the canvas.toDataURL("image/png") to server and downloading the image, but the image is not in proper shape .it seems the css(nvd3.css) is not getting applied.
Any help will be really heplfull.
Thanks,
chandan

A: i have the same requirement and "example of how to export a png directly from an svg" solved my problem (internally it adopted svg-crowbar code. basically, you need to "explicitly set css style" for all svg element.


text:
Q: Error in testing function call with Karma in AngularJs I am trying to implement a very simple application with AngularJs based on the tutorial that there is in it's website. I want to perform unit testing with Karma.
My files:
karma.conf.js
module.exports = function(config) {
config.set({

    basePath: '',

    files: [
        'angular/angular.min.js',
        'angular/angular-resource.min.js',
        'angular/angular-route.min.js',
        'angular/angular-mocks.js',
        'app.module.js',
        'phone-list/phone-list.module.js',
        'phone-list/phone-list.component.js',
        'phone-detail/phone-detail.module.js',
        'phone-detail/phone-detail.component.js',
        'core/core.module.js',
        'core/phone/phone.module.js',
        'core/phone/phone.service.js',
        'phone-list/phone-list.component.spec.js'
    ],

    autoWatch: true,
    frameworks: ['jasmine'],
    browsers: ['Chrome', 'Firefox'],
    plugins: [
        'karma-chrome-launcher',
        'karma-firefox-launcher',
        'karma-jasmine'
    ]
});
};

phone-list.component.js
'use strict';
 angular.
 module('phoneList').
 component('phoneList', {
 templateUrl: 'phone-list/phone-list.template.html',
 controller: ['Phone', function PhoneListController(Phone) {
        var self = this;
        self.$onInit = initializeData;

        function initializeData () {
            self.orderProp = 'age';
            self.loadPhones();
        }

        function testFunction() {
            return 'test';
        }

        self.loadPhones = function() {
            self.phones = Phone.query(testFunction);
        };

    }
]
});

phone-list.component.spec.js
'use strict';

describe('phoneList', function() {

beforeEach(module('phoneList'));

describe('PhoneListController', function() {
  var ctrl, mockPhone, phoneData;

  phoneData = {
      "age": 1,
      "id": "motorola",
      "imageUrl": "img/phones/motorola.jpg",
      "name": "Motorola XOOM with Wi-Fi",
      "snippet": "The Next, Next Generation,Experience"
  };

  beforeEach(module('phoneList', function($provide) {
      mockPhone = {
          query: function () {
              return phoneData;
          }
      };
      $provide.value('Phone', mockPhone);
  }));

beforeEach(inject(function($componentController) {
    ctrl = $componentController('phoneList');
}));

  it('should initialize controller data and check a function call', function() {
    jasmine.addCustomEqualityTester(angular.equals);
    spyOn(ctrl, 'loadPhones').and.callThrough();
    spyOn(mockPhone, 'query').and.callThrough();
    ctrl.$onInit();
    expect(ctrl.loadPhones).toHaveBeenCalled();
    expect(ctrl.phones).toEqual(phoneData);
    expect(mockPhone.query).toHaveBeenCalledWith(jasmine.any(Function));
  });
});
});

phone.service.js
angular
.module('core.phone')
.factory('Phone', ['$resource',
function ($resource) {
    return $resource('phones/phones.json', {}, {
        query: {
            method: 'GET',
            params: {phoneId: phones},
            isArray: true
        }
    });
}
]);

package.json at C:\WebstormProjects\testing\app\node_modules\karma
   {
  "_args": [
    [
      {
        "raw": "karma",
        "scope": null,
        "escapedName": "karma",
        "name": "karma",
        "rawSpec": "",
        "spec": "latest",
        "type": "tag"
      },
      "C:\\WebstormProjects\\testing\\app"
    ]
  ],
  "_from": "karma@latest",
  "_id": "karma@1.3.0",
  "_inCache": true,
  "_installable": true,
  "_location": "/karma",
  "_nodeVersion": "6.3.0",
  "_npmOperationalInternal": {
    "host": "packages-12-west.internal.npmjs.com",
    "tmp": "tmp/karma-1.3.0.tgz_1473445878695_0.6908389490563422"
  },
  "_npmUser": {
     ...
  },
  "_npmVersion": "3.10.3",
  "_phantomChildren": {},
  "_requested": {
    "raw": "karma",
    "scope": null,
    "escapedName": "karma",
    "name": "karma",
    "rawSpec": "",
    "spec": "latest",
    "type": "tag"
  },
  "_requiredBy": [
    "#DEV:/",
    "#USER"
  ],
  "_resolved": "https://registry.npmjs.org/karma/-/karma-1.3.0.tgz",
  "_shasum": "b2b94e8f499fadd0069d54f9aef4a4d48ec5cc1f",
  "_shrinkwrap": null,
  "_spec": "karma",
  "_where": "C:\\WebstormProjects\\testing\\app",
  "author": {
    ...
  },
  "bin": {
    "karma": "./bin/karma"
  },
  "bugs": {
    "url": "https://github.com/karma-runner/karma/issues"
  },
  "config": {
    "ghooks": {
      "pre-commit": "npm run lint",
      "commit-msg": "validate-commit-msg"
    }
  },
  "contributors": [
    ....

  ],
  "dependencies": {
    "bluebird": "^3.3.0",
    "body-parser": "^1.12.4",
    "chokidar": "^1.4.1",
    "colors": "^1.1.0",
    "combine-lists": "^1.0.0",
    "connect": "^3.3.5",
    "core-js": "^2.2.0",
    "di": "^0.0.1",
    "dom-serialize": "^2.2.0",
    "expand-braces": "^0.1.1",
    "glob": "^7.0.3",
    "graceful-fs": "^4.1.2",
    "http-proxy": "^1.13.0",
    "isbinaryfile": "^3.0.0",
    "lodash": "^3.8.0",
    "log4js": "^0.6.31",
    "mime": "^1.3.4",
    "minimatch": "^3.0.0",
    "optimist": "^0.6.1",
    "qjobs": "^1.1.4",
    "range-parser": "^1.2.0",
    "rimraf": "^2.3.3",
    "socket.io": "1.4.7",
    "source-map": "^0.5.3",
    "tmp": "0.0.28",
    "useragent": "^2.1.9"
  },
  "description": "Spectacular Test Runner for JavaScript.",
  "devDependencies": {
    "LiveScript": "^1.3.0",
    "babel": "^6.5.2",
    "babel-preset-es2015": "^6.9.0",
    "babel-register": "^6.9.0",
    "chai": "^3.3.0",
    "chai-as-promised": "^5.0.0",
    "chai-subset": "^1.2.2",
    "coffee-script": "^1.9.2",
    "cucumber": "^1.2.0",
    "eslint": "^2.3.0",
    "eslint-config-standard": "^5.1.0",
    "eslint-plugin-promise": "^1.0.8",
    "eslint-plugin-react": "^5.1.1",
    "eslint-plugin-standard": "^1.3.1",
    "ghooks": "^1.1.0",
    "grunt": "^1.0.0",
    "grunt-auto-release": "^0.0.6",
    "grunt-browserify": "^5.0.0",
    "grunt-bump": "^0.8.0",
    "grunt-cli": "^1.1.0",
    "grunt-contrib-watch": "^1.0.0",
    "grunt-conventional-changelog": "^6.0.1",
    "grunt-conventional-github-releaser": "^1.0.0",
    "grunt-cucumberjs": "^0.10.2",
    "grunt-eslint": "^18.0.0",
    "grunt-mocha-test": "^0.12.7",
    "grunt-npm": "0.0.2",
    "jasmine-core": "^2.3.4",
    "json3": "^3.3.2",
    "karma-browserify": "^5.0.1",
    "karma-browserstack-launcher": "^1.0.0",
    "karma-chai": "^0.1.0",
    "karma-chrome-launcher": "*",
    "karma-coffee-preprocessor": "*",
    "karma-commonjs": "*",
    "karma-coverage": "*",
    "karma-firefox-launcher": "*",
    "karma-growl-reporter": "*",
    "karma-html2js-preprocessor": "*",
    "karma-jasmine": "^1.0.2",
    "karma-junit-reporter": "*",
    "karma-live-preprocessor": "*",
    "karma-mocha": "^1.0.1",
    "karma-mocha-reporter": "^2.0.0",
    "karma-ng-scenario": "*",
    "karma-phantomjs-launcher": "*",
    "karma-qunit": "*",
    "karma-requirejs": "*",
    "karma-sauce-launcher": "*",
    "karma-script-launcher": "^1.0.0",
    "load-grunt-tasks": "^3.1.0",
    "mkdirp": "^0.5.0",
    "mocha": "^2.4.1",
    "mocks": "^0.0.15",
    "phantomjs-prebuilt": "^2.1.3",
    "proxyquire": "^1.5.0",
    "qunitjs": "^1.21.0",
    "requirejs": "^2.1.20",
    "sinon": "^1.17.5",
    "sinon-chai": "^2.7.0",
    "supertest": "^2.0.0",
    "supertest-as-promised": "^3.0.0",
    "timer-shim": "^0.3.0",
    "validate-commit-msg": "^2.4.1",
    "which": "^1.1.1"
  },
  "directories": {},
  "dist": {
    "shasum": "b2b94e8f499fadd0069d54f9aef4a4d48ec5cc1f",
    "tarball": "https://registry.npmjs.org/karma/-/karma-1.3.0.tgz"
  },
  "engines": {
    "node": "0.10 || 0.12 || 4 || 5 || 6"
  },
  "gitHead": "9cd65cd0d9b063d54953013105904e9b55822f47",
  "homepage": "http://karma-runner.github.io/",
  "keywords": [
    "karma",
    "spectacular",
    "runner",
    "karma",
    "js",
    "javascript",
    "testing",
    "test",
    "remote",
    "execution"
  ],
  "license": "MIT",
  "main": "./lib/index",
  "maintainers": [
    ...
  ],
  "name": "karma",
  "optionalDependencies": {},
  "readme": "ERROR: No README data found!",
  "repository": {
    "type": "git",
    "url": "git://github.com/karma-runner/karma.git"
  },
  "scripts": {
    "appveyor": "npm run lint && npm run build && npm run test:appveyor",
    "build": "grunt build",
    "init": "rm -rf node_modules/karma && cd node_modules && ln -nsf ../ karma && cd ../",
    "init:windows": "(IF EXIST node_modules\\karma (rmdir node_modules\\karma /S /q)) && npm run link",
    "link": "node --eval \"path=require('path'); require('fs').symlinkSync(path.resolve(__dirname), path.resolve(__dirname, 'node_modules', 'karma'), 'junction')\"",
    "lint": "grunt lint",
    "test": "grunt test",
    "test:appveyor": "grunt test-appveyor",
    "test:integration": "./scripts/integration-tests.sh",
    "travis": "npm run lint && npm run build && npm test && npm run test:integration",
    "unlink": "node --eval \"require('fs').unlinkSync(require('path').resolve(__dirname, 'node_modules', 'karma'))\""
  },
  "version": "1.3.0"
}

When I run the tests, I get the following error:
   Expected spy query to have been called with [ <jasmine.any(Function)> ] but actual calls were [ Function ].
        at Object.<anonymous> (phone-list/phone-list.component.spec.js:40:31)

Is my testing strategy wrong? Why I get this error?


text:
Q: Relativistic factor between coordinate acceleration and proper acceleration I did a recent question about relativistic kinematics here: Generalizing a relativistic kinematics formula for spatial-acceleration dependence.
I have a confusion. In the textbooks I've seen, they put the relationship between proper acceleration and coordinate acceleration as
$$ \alpha = \gamma^3 \frac{dv}{dt} $$
However, when I try to do the derivation myself, I get a factor of $\gamma^4$ instead. I'm not sure where the error is.
My derivation is like this:
$$\frac{dx}{d \tau} = \frac{dx}{dt} \frac{dt}{d \tau} = \gamma \frac{dx}{dt}$$
where we used $\frac{dt}{d \tau} = \gamma $
Now,
$$\frac{d^2 x}{d \tau^2} = \frac{ d}{d \tau}( \gamma \frac{dx}{dt}) = \frac{d \gamma}{d \tau} \frac{dx}{dt} + \gamma^2 \frac{ d^2 x}{dt^2} $$
$$\frac{d \gamma}{d \tau} = \gamma \frac{d \gamma}{dt} = \gamma (\frac{ \gamma^3 }{c^2} \frac{dx}{dt} \frac{d^2 x}{dt^2})$$
$$\frac{d^2 x}{d \tau^2} =  \gamma^4 \frac{v^2}{c^2} \frac{d^2 x}{dt^2} + \gamma^2 \frac{d^2 x}{dt^2} = \gamma^2 \frac{d^2 x}{dt^2} (\gamma^2 \frac{v^2}{c^2} + 1) = \gamma^4 \frac{d^2 x}{dt^2}$$
where on the last step, $v= \frac{dx}{dt}$ .
I don't understand where is the mistake.

A: From Wiki:

In the standard inertial coordinates of special relativity, for
  unidirectional motion, proper acceleration is the rate of change of
  proper velocity with respect to coordinate time.

You're instead finding the rate of change of proper velocity with respect to proper time and, so, are picking up an extra Lorentz factor.  See Four-acceleration.

A: Proper acceleration is not the same as the four-vector acceleration. Proper acceleration is defined as a Lorentz-invariant acceleration, that is, an acceleration that all inertial observers agree upon. Let's define a few concepts:
The proper velocity $\vec{u}$ is the derivative of the position with respect to proper time:
$$
\vec{u} = \frac{\text{d}\vec{x}}{\text{d}\tau}=\gamma\vec{v}.
$$
The proper velocity is the spacial component of the velocity four-vector $\boldsymbol{U}$
$$
\boldsymbol{U} = (c\gamma,\vec{u}),
$$
and the acceleration four-vector $\boldsymbol{A}$ is
$$
\boldsymbol{A} = \frac{\text{d}\boldsymbol{U}}{\text{d}\tau} = \left(c\frac{\text{d}\gamma}{\text{d}\tau},\frac{\text{d}\vec{u}}{\text{d}\tau} \right).
$$
The relativistic scalar product $\boldsymbol{A}\bullet\boldsymbol{A} = A_0^2 - (\vec{A})^2$ is Lorentz-invariant. We get
$$
\boldsymbol{A}\bullet\boldsymbol{A} = c^2\left(\frac{\text{d}\gamma}{\text{d}\tau}\right)^2 - \left(\frac{\text{d}\vec{u}}{\text{d}\tau}\right)^2.
$$
Now,
$$
\frac{\text{d}\gamma}{\text{d}\tau} = \gamma^4\frac{\vec{v}\cdot\vec{a}}{c^2},
$$
where $\vec{a} = \text{d}\vec{v}/\text{d}t$ is the classical acceleration vector. On the other hand,
$$
\frac{\text{d}\vec{u}}{\text{d}\tau} = \frac{\text{d}\gamma}{\text{d}\tau}\vec{v} + \gamma\frac{\text{d}\vec{v}}{\text{d}\tau} = \gamma^4\left(\frac{\vec{v}\cdot\vec{a}}{c^2}\right)\vec{v} + \gamma^2\vec{a}.
$$
Let's call $v_\parallel$ the component $\vec{v}$ parallel to $\vec{a}$, and $v_\perp$ the perpendicular component. It follows that $\vec{v}\cdot\vec{a}=v_\parallel a$, so that
$$
\begin{align}
\boldsymbol{A}\bullet\boldsymbol{A} &=
 \gamma^8\frac{v_\parallel^2 a^2}{c^2} - \gamma^8\left(\frac{v_\parallel^2 a^2}{c^2}\right)\left(\frac{v^2}{c^2}\right) - 2\gamma^6\frac{v_\parallel^2 a^2}{c^2} - \gamma^4a^2\\
&= \gamma^6\frac{v_\parallel^2 a^2}{c^2} - 2\gamma^6\frac{v_\parallel^2 a^2}{c^2} - \gamma^4a^2\\
&= -\gamma^6\frac{v_\parallel^2 a^2}{c^2} - \gamma^6a^2\left(1 - \frac{v_\parallel^2}{c^2}- \frac{v_\perp^2}{c^2}\right)\\
&= -\frac{\gamma^6}{\gamma_\perp^2} a^2,
\end{align}
$$
where
$$
\gamma_\perp = \frac{1}{\sqrt{1 - v_\perp^2/c^2}}.
$$
So $\boldsymbol{A}\bullet\boldsymbol{A}$ is always negative. If we now define the proper acceleration vector $\vec{\alpha}$
$$
\vec{\alpha} = \frac{\gamma^3}{\gamma_\perp} \vec{a} = \frac{\gamma^3}{\gamma_\perp}\frac{\text{d}\vec{v}}{\text{d}t},
$$
then $\alpha^2 = -\boldsymbol{A}\bullet\boldsymbol{A}$ is indeed Lorentz-invariant. This is why the proper acceleration is defined like this.
If $v_\perp=0$, then the formula reduces to
$$
\vec{\alpha} =\gamma^3 \frac{\text{d}\vec{v}}{\text{d}t} = \frac{\text{d}\vec{u}}{\text{d}t}.
$$
So in this case, the proper acceleration is the derivative of the proper velocity with respect to coordinate time $t$, not the proper time. The derivative of the proper velocity with respect to proper time $\tau$ is in fact the spatial part of the four-vector acceleration
$$
\vec{A} = \frac{\text{d}\vec{u}}{\text{d}\tau} = \frac{\text{d}^2\vec{x}}{\text{d}\tau^2}.
$$
That's where the extra $\gamma$ comes from.

A: The proper acceleration in the formula you're trying to derive refers to what's measured in the inertial frame instantaneously co-moving with the particle, and not in the accelerated co-moving frame of the particle where the measured acceleration is zero.
This is how I would do the derivation using either a 3-vector or 4-vector approach:
 3-vector approach
Let frames $S$ and $S'$ move at a constant velocity, and $p$ be an accelerated point. The strategy is to find how the acceleration of $p$ transforms between $S$ and $S'$, and then to make the velocity of $S'$ equal to the instantaneous velocity of $p$ which then gives us the relationship between the proper acceleration and lab acceleration of $p$. Without loss of generality and to simplify things, $p$ accelerates along $x$, and $S'$ moves along the $x-\text{axis}$ at constant velocity $v$ as usual.
In $S'$, the coordinates of $p$ are $(x',y',z',t')$ which can be expressed in terms of the $S$ coordinates via the Lorentz transformations. Using these we can also find $\frac{dt'}{dt}$:
$$ x' =\gamma(x-vt),\quad t' = \gamma(t - vx/c^2),\quad \frac{dt'}{dt}= \gamma(1-\frac{vu_x}{c^2})$$
$p$ is accelerated along the x'-axis:
$$\begin{align*}
\frac{d^2x'}{dt'^2}
&=\frac{d}{dt'}\frac{dt}{dt'}\frac{d}{dt}\gamma(x - vt)
=\frac{dt}{dt'}\frac{d}{dt}\frac{u_x - v}{1-\frac{vu_x}{c^2}}
=\frac{1}{\gamma(1-\frac{vu_x)}{c^2}}
\cdot
\frac{1}{\gamma^2(1-\frac{vu_x}{c^2})^2}
\frac{d^2x}{dt^2}\\\
&=\frac{1}{\gamma^3(1-\frac{vu_x}{c^2})^3}\frac{d^2x}{dt^2}
\end{align*}$$
We now make $S'$ the co-moving and therefore proper frame of $p$ with $u_x$ the velocity of $p$ in $S$ which we now set equal to $v$, finally giving
$$\frac{d^2x'}{dt'^2} = \gamma^3\frac{d^2x}{dt^2}$$
 4-vector approach
The four acceleration is given by
$$\left(
{\gamma_u}^4\frac{\mathbf{a\cdot u}}{c},
{\gamma_u}^2\mathbf{a}+
{\gamma_u}^4\frac{(\mathbf{a\cdot u)}}{c^2}\mathbf{u}
\right)$$
In the proper frame where $\mathbf{u=0}$, this immediately simplifies to $(0,\mathbf{a_p})$. We just Lorentz tranform the time part to establish the relationship between the lab and proper accelerations
$$
\begin{align*}
\gamma^4\frac{\mathbf{a_lv}}{c^2}&=
\gamma\left(0 + \frac{\mathbf{va_p}}{c^2}\right)\\
\mathbf{a_p}&=\gamma^3\mathbf{a_l}
\end{align*}
$$
method in question
It's not clear to me what your strategy is, but it could be made to work based upon the 3-vector approach above:

$$\frac{dx}{d \tau} = \frac{dx}{dt} \frac{dt}{d \tau} = \gamma \frac{dx}{dt}$$
where we used $\frac{dt}{d \tau} = \gamma $

Correct

Now,
$$\frac{d^2 x}{d \tau^2} = \frac{ d}{d \tau}( \gamma \frac{dx}{dt}) = \frac{d \gamma}{d \tau} \frac{dx}{dt} + \gamma^2 \frac{ d^2 x}{dt^2} $$

This won't work because $\gamma$ is a function of the relative velocity $v$ between the two frames where the acceleration is being measured, and we keep this velocity constant:
$$\frac{d^2 x}{d \tau^2} = \frac{ d}{d \tau}( \gamma \frac{dx}{dt}) = \gamma^2 \frac{ d^2 x}{dt^2} $$
The term on the RHS isn't an acceleration for any frame because it's mixing the space coordinate from the proper frame with the time coordinate from the lab frame. You need to transform $x$ to $x'$ using the Lorentz transformation $x=\gamma(x' + vt)$ so that finally, keeping $\gamma$ and $v$ constant:
$$\frac{d^2 x}{d \tau^2} = \gamma^2 \frac {d^2x}{dt^2} = \gamma^2\frac {d^2}{dt^2}\gamma (x' + vt)= \gamma^3\frac{d^2x'}{dt^2}$$


text:
Q: What is a Shockley-Read current? What is a Shockley-Read current? Googling it brings up nothing. Is it possible this is some obscure name for a type of diode current? I know what the Shockley-Read-Hall process is, is it related to that?

A: The Shockley-Read current is the current in a pn-junction (or bipolar transistor) that is due to the electron-hole recombination or generation in the depletion zone according to the Shockley-Read-Hall mechanism involving the capture/emission of charge carriers on deep levels in the energy band gap. It is particularly important in the semiconductor silicon where its is the dominant current in pn-junctions as opposed to the so-called diffusion current of the original Shockley diode model.
Historically, this recombination/generation mechanism has been described by W. Shockley and W.T. Read in a Physical Review article published in 1952. The same mechanism has been proposed independently by R.N. Hall in Physical Review articles in 1951 and 1952.


text:
Q: Prevent user from logging in directly to windows 2003 server but allow workstation and RDP log in? I want to be able to prevent a user from sitting down directly at our server and log in but allow them to remote desktop in or log in from workstation. We are on a domain with windows 2003 server.

A: There are four Group Policies that will do exactly what you want:

*

*Allow log on locally

*Deny log on locally

*Allow log on through Remote Desktop Services

*Deny log on through Remote Desktop Services
By combining them, you can define which users (or groups) can (and cannot) log on to the server console and/or via Remote Desktop.
All of them can be found in Computer Configuration > Windows Settings > Security Settings > Local Policies > User Rights Assignment


text:
Q: Extract information from a 3-D graph I used the plot3 method for creating a 3-D graph. Now I want to extract all the points with z > 0.
How can I do this?

A: First you need to have the data used to make the plot; if you have them directly, that is the simple case.  If not - for example, if you have a plot from some other script, or a figure file saved by someone else that you're just loading - you can get the data from the plot like this:
%# make sure the plot is the current axes object by clicking on it
%# or else use the actual axes handle instead of gca
X = get(gca,'xdata');
Y = get(gca,'ydata');
Z = get(gca,'zdata');

Next, use logical indexing:
index = Z > 0;
X_of_interest = X(index);
Y_of_interest = Y(index);
Z_of_interest = Z(index);

The new variables contain the X,Y,Z values of all points where the condition Z>0 is true.


text:
Q: asp.net vb - update database field value automatically when another value is added elsewhere I have two tables: HolidayRequests & HolidayEntitlement
Within the Holiday Requests I have 1 field:

*

*Days

When a staff member adds a holiday request it is stored as a number in the holiday requests table in days field (there are multiple requests with different days)
Within the HolidayEntitlement table I have 3 fields:

*

*Entitlement

*Taken

*Remaining

When a staff member adds a holiday request I want it to update both the taken and Remaining with something like...
Taken = (sum)Days where staffid = staffid
Remaining = Entitlement - Taken
I've got no idea how to go about doing this. The idea is similar to that of stock management...
can anyone point me in the right direction so I can get started

A: *

*You can use a stored procedure & issue a transaction whenever the parent field is updated

*Use a trigger to fire on every insert/update on parent table row & update the 2nd table

A: You can implement business logic like that:

*

*in the database with triggers (see the other answers)

*in your vb code with Linq2sql using Partial Methods:

Example from http://msdn.microsoft.com/en-us/library/bb546176.aspx
Partial Class Customer
    Private Sub OnAddressChanged()
        ' Insert business logic here.
    End Sub
End Class


text: Q: Counter example for Wronskian Concept . I know the result that if $y_1$ and $y_2$ are two solutions of the differential equation $$y''+p(x)y'+Q(x)y=f(x)$$ then Wronskian $W(y_1,y_2)=ce^{\int -p(x)dx}$ of $y_1$ and $y_2$ is given by Abels Theorem ($ P,Q $ and $f $ are continuous functions in some open interval I). So by Abels theorem Wronskian does not change sign because of constant $c$. Now I am searching counter example of differential equation for which coefficient functions are discontinuous so that Wronskian changes Sign i.e. Wronskian some time becomes positive and sometimes negative. Please provide some counter example. Thank you.


text:
Q: insert a string at specific position in a file by SED awk I have a string which i need to insert at a specific position in a file :
The file contains multiple semicolons(;) i need to insert the string just before the last ";"
Is this possible with SED ?
Please do post the explanation with the command as I am new to shell scripting
before :
adad;sfs;sdfsf;fsdfs

string = jjjjj
after
adad;sfs;sdfsf jjjjj;fsdfs

Thanks in advance

A: This might work for you:
echo 'adad;sfs;sdfsf;fsdfs'| sed 's/\(.*\);/\1 jjjjj;/'
adad;sfs;sdfsf jjjjj;fsdfs

The \(.*\) is greedy and swallows the whole line, the ; makes the regexp backtrack to the last ;. The \(.*\) make s a back reference \1. Put all together in the RHS of the s command means insert jjjjj before the last ;.

A: sed 's/\([^;]*\)\(;[^;]*;$\)/\1jjjjj\2/' filename

(substitute jjjjj with what you need to insert).
Example:
$ echo 'adad;sfs;sdfsf;fsdfs;' | sed 's/\([^;]*\)\(;[^;]*;$\)/\1jjjjj\2/'
adad;sfs;sdfsfjjjjj;fsdfs;

Explanation:
sed finds the following pattern: \([^;]*\)\(;[^;]*;$\). Escaped round brackets (\(, \)) form numbered groups so we can refer to them later as \1 and \2.
[^;]* is "everything but ;, repeated any number of times.
$ means end of the line.
Then it changes it to \1jjjjj\2.
\1 and \2 are groups matched in first and second round brackets.

A: For now, the shorter solution using sed : =)
sed -r 's@;([^;]+);$@; jjjjj;\1@' <<< 'adad;sfs;sdfsf;fsdfs;'

*

*-r option stands for extented Regexp

*@ is the delimiter, the known / separator can be substituted to any other character

*we match what's finishing by anything that's not a ; with the ; final one, $ mean end of the line

*the last part from my explanation is captured with ()

*finally, we substitute the matching part by adding "; jjjj" ans concatenate it with the captured part

Edit: POSIX version (more portable) :
echo 'adad;sfs;sdfsf;fsdfs;' | sed 's@;\([^;]\+\);$@; jjjjj;\1@'

A: Something like this may work for you:
echo "adad;sfs;sdfsf;fsdfs"| awk 'BEGIN{FS=OFS=";"} {$(NF-1)=$(NF-1) " jjjjj"; print}'

OUTPUT:
adad;sfs;sdfsf jjjjj;fsdfs

Explanation: awk starts with setting FS (field separator) and OFS (output field separator) as semi colon ;. NF in awk stands for number of fields. $(NF-1) thus means last-1 field. In this awk command {$(NF-1)=$(NF-1) " jjjjj" I am just appending jjjjj to last-1 field.

A: sed -e 's/\(;[^;]*\)$/ jjjj\1/'

Inserts jjjj before the part where a semicolon is followed by any number of non-semicolons ([^;]*) at the end of the line $. \1 is called a backreference and contains the characters matched between \( and \).
UPDATE: Since the sample input has no longer a ";" at the end.

A: echo 'adad;sfs;sdfsf;fsdfs;' | sed -r 's/(.*);(.*);/\1 jjjj;\2;/'

You don't need the negation of ; because sed is by default greedy, and will pick as much characters as it can.


text:
Q: getKeyFrame method accepts a float that is continuously incrementing. Why? I am following a libgdx book. In it, the author uses Animation class to play an animation. This is the relevant code:
public class Flappee{

private float animationTimer = 0;

private static final float FRAME_DURATION=0.25f;

public Flappee(Texture texture){

    TextureRegion[][] flappeeTextures = new TextureRegion(texture).split(118,118);
    collisionCircle = new Circle(x,y,COLLISION_RADIUS);
    this.animation = new Animation(FRAME_DURATION,flappeeTextures[0][0],flappeeTextures[0][1]);
    animation.setPlayMode(Animation.PlayMode.LOOP);
}

public void update(float delta){
        animationTimer+=delta; //called in render method of ScreenAdapter class
}

public void draw(SpriteBatch batch){
        TextureRegion texture = animation.getKeyFrame(animationTimer);
        batch.draw(//drawing commands);
    }
}

I don't understand why animationTimer needs to be incremented every render loop. As you can see it is crucial to getKeyFrame to return the right textureRegion. I guess it has something to do with looping the same animation all the time. May I ask for additional explanation on this topic?

A: The delta value passed to render is the amount of time since the last frame, so by adding it to animationTimer each time render is called means that animationTimer holds the amount of time since the animation started running.
This is needed to work out what frame to display at any given time. So if you wanted your animation to run at 5 frames per second, and animationTimer was 400ms, then it can work out that it should display frame numer 2.
It doesn't simply pick the next frame each time render is called because that would tie the animation speed to the framerate, which is not always desirable. Also framrates are not constant so this approach ensures any inconsistencies are smoothed out.


text:
Q: Modification of Atom-Field interaction Hamiltonian in the Knight optics textbook I am reading Quantum optics textbook of Peter Knight.
From the Eq 4.3
$
\hat{H} = \frac{1}{2m}[\hat{P}+e\hat{A}]^2-e\Phi + V(r)
$
Using
$
\hat{H}' = \hat{R}\hat{H}\hat{R}^{\dagger} + i\hbar\frac{\partial \hat{R} }{\partial t}\hat{R}^{\dagger}
$
where $\hat{R}$ = exp$(-ie\chi(\vec{r},t)/\hbar )$
The Hamiltonian is modified by
$
\hat{H} = \frac{1}{2m}[\hat{P}+e(\hat{A}+\nabla\chi) ]^2-e(\Phi-\frac{\partial \chi}{\partial t}) + V(r).
$
This procedure is a little complicated for me.
I tried the first part of the equation
$
\hat{R}\hat{P}^2\hat{R}^{\dagger} \\
= \hat{R} *-\hbar^2\nabla\cdot\nabla(\hat{R}^{\dagger}) \\
= e\nabla\chi\cdot\hat{P}-e^2(\nabla\chi)^2
$
This catches away the $\hat{P}^2$ part that should be survived.
What is my fault??

A: Chapter 14 of https://onlinelibrary.wiley.com/doi/book/10.1002/3527602976 explains very well these steps, in my opinion.
Instead of developing the term $[P+eA]^2$ it is perhaps better to observe that
$$R[P+eA]^2R^{\dagger}=R[P+eA][P+eA]R^{\dagger}=R[P+eA]I[P+eA]R^{\dagger}=R[P+eA]RR^{\dagger}[P+eA]R^{\dagger}$$
where we use $RR^{\dagger}=I$, since $R$ is unitary. We conclude that
$$R[P+eA]^2R^{\dagger}=\{R[P+eA]R^{\dagger}\}^2$$ and the result follows more easilly.


text:
Q: clearing and changing content of div I'm trying to replace the content of comments div with the new comments by loading it again and replacing the old comments. When i change the content of the div, it replaces the first comment only and repeat the whole comment:
here is the comments div :
<?php
$comment_qry = mysqli_query($conn, "SELECT * FROM comments WHERE post_id='$post_row[id]' ORDER BY id DESC");
while($comment_row = mysqli_fetch_array($comment_qry)){
?>

        <p onclick="report_var(<?php echo $post_row['id']; ?>, <?php echo $comment_row['user_id']; ?>);">report

user: <?php echo $comment_row['user_id']; ?>

date: <?php echo date("Y-m-d", $comment_row['date']); ?>

content: <?php echo $comment_row['content']; ?>

        <?php if($post_row['user_id'] == $my_id or $comment_row['user_id'] == $my_id or $admin == 1){ ?>

<span onclick="comment_remove(<?php echo $comment_row['id']; ?>, <?php echo $comment_row['user_id']; ?>);">delete

        <?php } ?>

<?php } ?>

ajax code :
/////////////////////////comment function
function comment(post_id, poster_id)
{
loadXMLDoc("php/comment.php?post_id="+post_id+" content="+document.getElementById("content").value+"&poster_id="+poster_id,function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        document.getElementById("comments_div").innerHTML = xmlhttp.responseText;
    }
  });
}

comment.php :
<?php
$comment_qry = mysqli_query($conn, "SELECT * FROM comments WHERE post_id='$_GET[post_id]' ORDER BY id DESC");
while($comment_row = mysqli_fetch_array($comment_qry)){
?>

        <p onclick="report_var(<?php echo $post_row['id']; ?>, <?php echo $comment_row['user_id']; ?>);">report

user: <?php echo $comment_row['user_id']; ?>

date: <?php echo date("Y-m-d", $comment_row['date']); ?>

content: <?php echo $comment_row['content']; ?>

        <?php if($_GET['poster_id'] == $my_id or $comment_row['user_id'] == $my_id or $admin == 1){ ?>

<span onclick="comment_remove(<?php echo $comment_row['id']; ?>, <?php echo $comment_row['user_id']; ?>);">delete

        <?php } ?>

<?php } ?>

A: Your first code snippet is creating a separate comments_div for each comment. Then your JavaScript code snippet is just replacing the content of the first one.
You can fix it by putting the comments_div outside the the PHP while loop, and then using the same HTML output code inside that loop as you are in your third example (a div.comment per comment).
So, something like this in place of that first code snippet:

<?php
$comment_qry = mysqli_query($conn, "SELECT * FROM comments WHERE post_id='$post_row[id]' ORDER BY id DESC");
while($comment_row = mysqli_fetch_array($comment_qry)){
?>

        <p onclick="report_var(<?php echo $post_row['id']; ?>, <?php echo $comment_row['user_id']; ?>);">report

user: <?php echo $comment_row['user_id']; ?>

date: <?php echo date("Y-m-d", $comment_row['date']); ?>

content: <?php echo $comment_row['content']; ?>

        <?php if($_GET['poster_id'] == $my_id or $comment_row['user_id'] == $my_id or $admin == 1){ ?>

<span onclick="comment_remove(<?php echo $comment_row['id']; ?>, <?php echo $comment_row['user_id']; ?>);">delete

        <?php } ?>

<?php } ?>


text:
Q: How to find a vector in $\mathbb{R^3}$ knowing its plane and certain of its projections Let $a=2i -j+ k$, $b =i +2i- k$ and $c= i + j -2k$ be three vectors. If the vector $d$ is on the plane of $b$ and $c$ and its projection on $a$ is of magnitude $\sqrt{2/3}$, find $d$
later: So I know that the dot product of cross product of $a$ and $b$ the $d$ is zero. But how do I find the projection on $a$ ? That was exactly where I was stuck.

A: Hint: Try setting out all the information available explicitly.

*

*You know $d$ lives in the plane generated by $b$ and $c$. So $d=hb+jc$ for appropriate choices of real numbers $h$ and $j$.

*Also, the projection of $d$ onto $a$ has magnitude $\sqrt{2/3}$, so $\|d \cdot \hat{a}\| = \sqrt{2/3}$. Where by $\hat{a}$, I mean $\frac{a}{\|a\|}$.
(An important mathematical principle is that if $u$ is a unit vector, then the magnitude of the projection of a vector $a$ onto $u$ is just $\|a \cdot u\|$. If $u$ is not a unit vector, we have to correct this formula: in this case, the magnitude of the projection of $a$ onto $u$ is just $\|a \cdot \hat{u}\|$. This is the version of the principle used above.)
So in summary, you should write:
$$d=hb+jc, \qquad \|d \cdot \hat{a}\| = \sqrt{2/3}$$
near the top of your page.
Now spend some time struggling with the question. Its a game; you just push symbols around your page, and when you've found the values of $h$ and $j$ (which are real numbers), you win.
(While playing this game, keep in mind that the vectors $a,b$ and $c$ are already known, so they can be "plugged in" whenever you want. I wouldn't plug them in straight away; see how far you can get using vector notation first).
Also, I would advise computing $\hat{a}$ before you begin.


text:
Q: Error while adding shared pointer to the vector abstract base class:
#ifndef BUILDINGORG_H
#define BUILDINGORG_H
#include <iostream>
#include <memory>
#include <vector>

class BuildingOrg
{

public:
   BuildingOrg(int _id);
   virtual int addBuildingComponent(std::shared_ptr<BuildingOrg> buildingOrg,
                                    std::string _type) const;
   virtual void removeBuildingComponent(std::shared_ptr<BuildingOrg> buildingOrg);
   virtual void getInfo()=0;
private:
   int id;
   std::string type;
};

#endif // BUILDINGORG_H

concrete subclass:
#ifndef BUILDINGCOMPONENT_H
#define BUILDINGCOMPONENT_H
#include "buildingorg.h"

class BuildingComponent : public BuildingOrg
{
public:
    BuildingComponent(int _id);
    int addBuildingComponent(std::shared_ptr<BuildingOrg> _buildingOrg,
                             std::string _type) const override;
    void removeBuildingComponent(std::shared_ptr<BuildingOrg> buildingOrg)
                                                        override;
    void getInfo() override;
private:
    std::vector<std::shared_ptr<BuildingOrg>> building_Org;
};

#endif // BUILDINGCOMPONENT_H

Implementation of subclass:
#include "buildingcomponent.h"

BuildingComponent::BuildingComponent(int _id):
BuildingOrg(_id)
{
}

int BuildingComponent::addBuildingComponent(std::shared_ptr<BuildingOrg> _buildingOrg, std::string _type) const
{
    building_Org.push_back(_buildingOrg);// I am having error here
    return 1;
}

void BuildingComponent::removeBuildingComponent(std::shared_ptr<BuildingOrg> buildingOrg)
{

}

void BuildingComponent::getInfo()
{

}

When I try to put shared pointer in my Vector I get this nasty error;
I really don't know why I am getting the error:

cpp:10: error: passing 'const std::vector<std::shared_ptr<BuildingOrg> >' as 'this' argument of 'void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::shared_ptr<BuildingOrg>; _Alloc = std::allocator<std::shared_ptr<BuildingOrg> >; std::vector<_Tp, _Alloc>::value_type = std::shared_ptr<BuildingOrg>]' discards qualifiers [-fpermissive]
        building_Org.push_back(_buildingOrg);

I don't understand what is it saying.

A: The const in int addBuildingComponent(std::shared_ptr<BuildingOrg> _buildingOrg, std::string _type) const override; is a promise that addBuildingComponent will not change BuildingComponent. However, it tries to modify the member variable building_Org with the push_back()...
Removing the const from addBuildingComponent() should fix the error.
The discards qualifiers part of the error message refers to the conflict with the const qualifier of the member function.
C++ template related error messages can be notoriously difficult to parse at first, but it does get easier with practice :-)

A: You defined BuildingComponent::addBuildingComponent method as const (i.e. that it won't change member varialbles), but you are adding passed in value to a member list (i.e. changing the member variable).

A: *

*addBuildingComponent() is a const method.  within its scope, *this is const, and so this->building_Org is const.

*std::vector::push_back() is a non-const method.  So it can't be called in a context where the vector is const.


text:
Q: Replace particular character but not if it is inside () I'm looking for a one-line command to make a file more readable.  I want to replace all ; characters with newline unless it is inside a set of ().  This is on a firewall, so I can only use bash; no perl etc.
Example input:
ProductName: Threat Emulation; product_family: Threat; Destination: (countryname: United States; IP: 127.0.0.1; repetitions: 1) ; FileName: (file_name: myfile) ;

Expected output:
ProductName: Threat Emulation
product_family: Threat
Destination: (countryname: United States; IP: 127.0.0.1; repetitions: 1)
FileName: (file_name: myfile)

A: A little bit confusing regex for sed but workable
sed '
    :a                                                 #mark return point
    s/\(\(^\|)\)[^(]\+\);\s*\([^)]\+\((\|$\)\)/\1\n\3/ #remove ; between ) and (
    ta                                                 #repeat if substitute success
    s/[[:blank:];]\+$//                                #remove ; with spaces at end
    '

Breif regex explanation:

*

*^\|) from the line start or )

*[^(]\+ any symbols but (

*;\s* semicolon with possible space(s)

*(\|$ up to the line end or (

A: If you have awk, you can use the parentheses as field separators:
awk -F '[()]' '{
    for (i=1; i<=NF; i+=2) {
        if ($i) {
            gsub(/; */,"\n",$i)
            printf "%s", $i
            if ($(i+1)) printf "(%s)", $(i+1)
        }
    }
    print ""
}' <<END
ProductName: Threat Emulation; product_family: Threat; Destination: (countryname: United States; IP: 127.0.0.1; repetitions: 1) ; FileName: (file_name: myfile) ;
END

ProductName: Threat Emulation
product_family: Threat
Destination: (countryname: United States; IP: 127.0.0.1; repetitions: 1)
FileName: (file_name: myfile)

The trailing semicolon gives you a trailing newline.


text:
Q: A vector-output image generator alternative to ImageMagick's "convert" bash command I'm doing some txt->image generating using "convert" of ImageMagick. But it outputs only rasterized images, which saved in .eps is a bit useless. Is there any alternative to "convert" so that I can write bash scripts which, by parsing text files, gives me a vector output?

A: Found an answer. It's not a one-liner, but still does the job.
First, you have to render the text and measure it's dimensions - use conjure on a template file, i.e.:
<?xml version="1.0" encoding="UTF-8"?>
<image>
   <query-font-metrics text="English (American)" font="Helvetica" pointsize="24" />
   <print output="%[msl:font-metrics.width]x%[msl:font-metrics.height]"/>
</image>

If the text is too big decrease if it's too small increase it.
After receiving font size create an SVG file containing invisible rectangle with the dimensions given and text centred in it. Then convert it using Inkscape to .eps
TA-DA


text:
Q: Laravel Eloquent: How do I refactor this eager load query into model scope method? I have a Card model which has many notes. And each note has an author. I am eager loading an individual card in a show action in my CardsController like so:
$card = $card->load(['notes' => function($query){
   $query->orderBy('created_at', 'desc')->limit(8);
}, 'notes.author']);

This query works. I want to now refactor this into a model scope so I can just call $card = Card::popular() in my controller. So add this method to my Card model:
public function scopePopular()
    {
        $results = $this->with(['notes' => function($query){
            $query->orderBy('created_at', 'desc')->limit(8);
        }, 'notes.author']);

        return $results;
    }

This messes up everything. I start getting unreadable template errors, when nothing should really break.
What am I doing wrong?

A: In order to use it as a static function and still be able to access the static methods within the class, use self:: instead of $this->.
public function scopePopular()
{
    $results = self::with(['notes' => function($query){
        $query->orderBy('created_at', 'desc')->limit(8);
    }, 'notes.author']);

    return $results;
}


text:
Q: Ajax responseText rendering multiple partial I'm trying to code a small popup window to add a new event on my app, using ruby on rails and Ajax.
I have implemented Ajax and get the action to works but the string sent within responseText contain more than the partial that I'm trying to display.
Looking at the server side, it makes sense due to the output it shows:
Started GET "/events/new.html" for 127.0.0.1 at 2018-01-11 21:58:18 +0100
Processing by EventsController#new as HTML
  Rendering events/new.html.erb within layouts/application
  Rendered shared/_error_messages.html.erb (0.4ms)
  Rendered events/new.html.erb within layouts/application (3.9ms)
  Rendered layouts/_rails_default.erb (223.3ms)
  Rendered layouts/_shim.html.erb (0.3ms)
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
  Rendered layouts/_header.html.erb (1.1ms)
  Rendered layouts/_footer.html.erb (0.4ms)
Completed 200 OK in 248ms (Views: 244.1ms | ActiveRecord: 0.2ms)

I can see that my server send the new.html from my events controller but then I got an error and some other rendered action. Anyone know why is that so ?
I am adding here the code I have implemented in case that may help
my_app.erb
$(".new_event_button").click(function(){
  console.log("click on add new event");
  // $("body").append("</%= escape_javascript(render 'events/new') %>");

  $("body").append("

");

  var req = new XMLHttpRequest();
  req.open("GET","/events/new.html");
  req.send();

  req.onreadystatechange = function () {
    console.log(req.readyState);
    if (req.readyState === 4) {
        $(".new_event_window").append(req.responseText);
    }
  }
});

events/new.html.erb

New Event

    <%= form_for(@event, url: create_event_path) do |f| %>
      <%= render 'shared/error_messages', object: f.object %>

      <%= f.label :title %>
      <%= f.text_field :title, class: 'form-control' %>

      <%= f.submit "Create my account", class: "btn btn-primary" %>

      <%= f.button :cancel, label: "Cancel", class: "btn btn-primary" %>
    <% end %>

and finally my event controller events_controller.erb
class EventsController < ApplicationController

  def new
    @event = Event.new
  end

  def create
  end
end

A: Have a try with another way like:
use link in views
<%= link_to "view", work_path(w), remote: true %>

Use respond js on your controller
respond_to do |format|
    format.js
end

In view.js.erb
$(".new_event_window").html("<%= j(render 'events/new') %>");
$('#myModal').modal('show')

A: Have you try this:
class EventsController < ApplicationController
  layout false, only: [:new]

  def new
    @event = Event.new
  end

  def create
  end
end


text:
Q: How should I integrate auto complete code into my current AngularJS code in following scenario? I'm a very newbie to AngularJS, so please try to understand my concerns.
I already have an HTML page and a controller written for it as follows :
bankDetails.html

                <form name="bankDetailsForm" action="save" method="POST"
                    ng-init="getBankDetails()">

                    <md-input-container class="md-block" style="margin-top:1em;">
                    Current Account Label <input
                        ng-model="bankDetails.currentAccountLabel" required
                        name="currentAccountLabel" ng-change="editField()">

Please enter valid Bank account
                            Label

                    </md-input-container>

                    <md-input-container class="md-block" style="margin-top:0px;">
                    Bank Name <input ng-model="bankDetails.bankName"
                        required name="bankName" ng-change="editField()">

Please enter valid Bank name

                    </md-input-container>

                    <md-input-container class="md-block" style="margin-top:0px;">
                    Branch <input ng-model="bankDetails.branch" required
                        name="branch" ng-change="editField()">

Please enter valid Branch

                    </md-input-container>

                    <md-input-container class="md-block" style="margin-top:0px;">
                    IFSC Code <input ng-model="bankDetails.ifscCode"
                        required name="ifscCode" ng-change="editField()">

Please enter valid IFSC code

                    </md-input-container>

                    <md-input-container class="md-block" style="margin-top:0px;">
                    Account Number <input
                        ng-model="bankDetails.accountNumber" required
                        name="accountNumber" ng-change="editField()">

Please enter valid Bank account
                            number

                    </md-input-container>

                    <md-input-container class="md-block" style="margin-top:0px;"
                        flex=100> Transaction Type <md-select
                        required ng-model="bankDetails.transactionType" ng-change="editField()"> <md-option
                        ng-repeat="type in transactionTypes" value="{{type}}">
                    {{type}} </md-option> </md-select>

Please select Transaction type

                    </md-input-container>

                    <md-button style="width:30%; display: block;margin:3em auto auto;"
                        ng-disabled="bankDetailsForm.$invalid" id="save" ng-click="save()"
                        class="md-raised md-primary">Save</md-button>
                </form>

                <md-content layout-padding>

                <form name="masterUserSettingsUploadFile" action="save"
                    method="POST">

                    <md-radio-group ng-model="data.documentType" class="textSizeMedium">

                        <md-radio-button value="Cancelled & crossed Cheque"
                            style="margin-top: 0.8em;"> Cancelled &
                            crossed Cheque </md-radio-button>

-
                            Organization name printed on same

                        <md-radio-button value="A Nodal Bank Letter"
                            style="margin-top: 1em;"> A Nodal Bank
                            Letter </md-radio-button>

- Stating
                            your current account details

                    </md-radio-group>

                        <input style="display: none;"
                            on-read-file="uploadFile($fileContent)" type="file"
                            name="file-6[]" id="file-6" class="inputfile inputfile-5"
                            data-multiple-caption="{count} files selected" multiple />  insert_drive_file
                        {{ data.documentType }}

                            <md-button class="md-icon-button"> delete</md-button>

                    <md-content class="messageBorder"
                        style="background-color:#FFC1C1;border-radius:5px;margin-top:1em;">
                    We would request you to please
                        send us all the documents Self Attested (Signature and Company
                        Stamp). Please use the sign which is matching with your ID proof
                        provided. </md-content>
                </form>

bankDetailsController.js
var app = angular.module('app_name');
var isEmpty = true;

app.controller("bankDetailsController", [ "$scope", "$http", "config", "$mdToast",
        function($scope, $http, config, $mdToast) {
            $scope.bankDetails = {};
            $scope.transactionTypes = {
                NEFT : "NEFT",
                IMPS : "IMPS",
                WALLET : "WALLET",
            };

            $scope.getBankDetails = function() {
                $http.get(config.webServicesUrl.bankDetails, headerConfig).success(function(data) {
                    if (data.body) {
                        $scope.bankDetails.currentAccountLabel = data.body.currentAccountLabel;
                        $scope.bankDetails.bankName = data.body.bankName;
                        $scope.bankDetails.branch = data.body.branch;
                        $scope.bankDetails.ifscCode = data.body.ifcsCode;
                        $scope.bankDetails.accountNumber = data.body.accountNumber;
                        //$scope.bankDetails.transactionTypes[NEFT] = $scope.transactionTypes.NEFT;
                        isEmpty = false;
                    }
                }).error(function(error) {
                    console.log("Error : " + error.error);
                });
            };

            $scope.save = function() {
                var bankDetails = {
                    currentAccountLabel : $scope.bankDetails.currentAccountLabel,
                    bankName : $scope.bankDetails.bankName,
                    branch : $scope.bankDetails.branch,
                    ifcsCode : $scope.bankDetails.ifscCode,
                    accountNumber : $scope.bankDetails.accountNumber,
                    transactionType : "NEFT",
                };
                if (isEmpty) {
                    $http.post(config.webServicesUrl.bankDetails, bankDetails, headerConfig).success(function(data) {
                        displayToastMessage("Your details saved successfully", $mdToast);
                        $( "#save" ).prop( "disabled", true );
                        isEmpty = false;
                    }).error(function(error) {
                        console.log("Error : " + error.error);
                    });
                } else {
                    $http.put(config.webServicesUrl.bankDetails, bankDetails, headerConfig).success(function(data) {
                        displayToastMessage("Your details saved successfully", $mdToast);
                        $( "#save" ).prop( "disabled", true );
                    }).error(function(error) {
                        console.log("Error : " + error.error);
                    });
                }
            }
            $scope.editField = function() {
                // Enable save button after user starts editing
                $( "#save" ).prop( "disabled", false );
            };
            $scope.data = {
                documentType : 'Cancelled & crossed Cheque'
            };

        } ]);

Now ignore all the code and concentrate only on the input field for IFSC code. I want to make this input field auto complete enabled. For it I referred following link
Autocomplete basic Usage in Angular Material
I want to implement the same code into my code on the field for IFSC code.
But since my controller file already contains a controller where should I write the JS code from link and what changes do I need to make in HTML code?
I've become clueless now. Please somebody help me out.
Thanks.
P.S. : All the necessary CSS and JS files have been already included in config file to use Angular Material in my project.

A: I'll give you an example.
 <md-autocomplete required
                  md-selected-item="selectedCode"
                  md-search-text="bankDetails.ifscCode"
                  md-items="temp in editField(bankDetails.ifscCode)"
                  md-item-text="temp.text"
                  placeholder="IFSC Code">
    <md-item-template>
        {{temp.text}}
    </md-item-template>
    <md-not-found>
        No states matching "{{bankDetails.ifscCode}}" were found.
    </md-not-found>
</md-autocomplete>

here, md-selected-item represents the the value you will select after showing the result.
md-search-text stores the text you write in the box.
md-items will be responsible for showing result depending upon the query. It will use a searchFunction which will be written in the controller. For Example,
$scope.editField = editField ;
editField = function(query){
   //use $http service to query server and resolve this promise and return  object or array to iterate.
};

md-item-text will display the text.
md-item-template is a template for each item returned by md-items.
md-not-found will display the message it there are no match found.
There are many other options available too. check out the offical documentation for more details.


text:
Q: auto compleate style changes hey i wanted to know how can i set my auto compleate from mui
to look like google search bar with the round container and round object
itryd this but this not working
const StyledAutocomplete = styled(Autocomplete)({
  "& .MuiAutocomplete-inputRoot": {
    color: "grey",
    backgroundColor: "white",
    borderRadius: "100px",
    height: "100%",
    padding: 5,

    "& .MuiOutlinedInput-notchedOutline": {
      borderColor: "transparent",
    },

    "&:hover .MuiOutlinedInput-notchedOutline": {
      borderColor: "transparent",
    },

    "&.Mui-focused .MuiOutlinedInput-notchedOutline": {
      borderColor: "transparent",
    },
  },

  "& .MuiOutlinedInput-root": { paddingRight: 10 },
});


text:
Q: Getting compiler error: Warning: [unchecked] unchecked call to addItem(E) as a member of the raw type JComboBox I'm making a shop in Netbeans IDE 8.2 and i can't compile, because of this error.  I tried fixig it by adding  to JComboBox but it didn't solved my problem. Web version of this app works fine but i can't compile it. When running with Xlint:Unchecked this is an warning: [unchecked] unchecked call to addItem(E) as a member of the raw type JComboBox
list.addItem(s);
where E is a type-variable:
E extends Object declared in class JComboBox
1 warning
package warstwa_klienta_desktop;

import java.awt.Dimension;
import java.util.ArrayList;

import java.util.Iterator;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;

public class Produkty_form extends JPanel  {
private JTable tabela_produktow;
MyTableModel model;
JComboBox<String> lista_produktow;

public void init() {
    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
    model = new MyTableModel();
    tabela_produktow = new JTable(model);
    table_content();

    tabela_produktow.setPreferredScrollableViewportSize(new Dimension(800, 100));
    tabela_produktow.setFillsViewportHeight(true);
    tabela_produktow.getSelectionModel().addListSelectionListener(new RowListener());
    add(new JScrollPane(tabela_produktow));
    JLabel lprodukty = new JLabel("Produkty");
    add(lprodukty);
    JComboBox<String>lista_produktow = new JComboBox<>();
    add(lista_produktow);
}

void table_content() {
    ArrayList<ArrayList<String>> produkty = GUI_main.getFacade().items();
    model.setData(produkty);
    tabela_produktow.repaint();
}

private void list_content(ArrayList<ArrayList<String>> col, JComboBox list)  {

    ArrayList<String> s;
    list.removeAllItems();
    Iterator<ArrayList<String>> iterator = col.iterator();
    while (iterator.hasNext()) {
        s = iterator.next();
        list.addItem(s);
    }
}

void print_produkty() {
    ArrayList<ArrayList<String>> help3 = GUI_main.getFacade().items();
    if (help3 != null) {
        list_content(help3, lista_produktow);
    }
}

private class RowListener implements ListSelectionListener {

    @Override
    public void valueChanged(ListSelectionEvent event) {
        if (event.getValueIsAdjusting()) {
            return;
        }
        print_produkty();
    }
}

class MyTableModel extends AbstractTableModel {

    private final String[] columnNames = {"Id produktu", "Nazwa", "Cena",
        "Promocja", "Data", "Cena brutto"};
    private ArrayList<ArrayList<String>> data;

    public void setData(ArrayList<ArrayList<String>> val) {
        data = val;
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public int getRowCount() {
        return data.size();
    }

    @Override
    public String getColumnName(int col) {
        return columnNames[col];
    }

    @Override
    public Object getValueAt(int row, int col) {
        return data.get(row).get(col);
    }

}

}

A: GUI_main looks like this
package warstwa_klienta_desktop;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.ejb.EJB;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import warstwa_biznesowa_ejb.Fasada_warstwy_biznesowej_ejbRemote;

public class GUI_main implements ActionListener {

    @EJB
    private static Fasada_warstwy_biznesowej_ejbRemote fasada;

    static JPanel cards;

    static CardLayout cl;

    static Pusty_form card0 = new Pusty_form();
    static Produkt_form card1 = new Produkt_form();
    static Produkty_form card2 = new Produkty_form();

    final static String PUSTY = "Pusty";
    final static String PRODUKT = "Produkt form";
    final static String PRODUKTY = "Produkty form";

    static public Fasada_warstwy_biznesowej_ejbRemote getFacade() {
        return fasada;
    }

    public JMenuBar createMenuBar() {
        JMenuBar menuBar;
        JMenu menu, submenu;
        JMenuItem menuItem;

        menuBar = new JMenuBar();

        menu = new JMenu("A Menu");
        menu.setMnemonic(KeyEvent.VK_A);
        menuBar.add(menu);

        menuItem = new JMenuItem(PRODUKT, KeyEvent.VK_P);
        menuItem.setAccelerator(KeyStroke.getKeyStroke(
                KeyEvent.VK_1, ActionEvent.ALT_MASK));
        menuItem.addActionListener(this);
        menu.add(menuItem);
        menuItem = new JMenuItem(PRODUKTY);
        menuItem.setMnemonic(KeyEvent.VK_R);
        menuItem.addActionListener(this);
        menu.add(menuItem);
        menuItem = new JMenuItem(PUSTY);
        menuItem.setMnemonic(KeyEvent.VK_U);
        menuItem.addActionListener(this);
        menu.add(menuItem);
        menu.addSeparator();

        submenu = new JMenu("A submenu");
        submenu.setMnemonic(KeyEvent.VK_A);

        menuItem = new JMenuItem(PUSTY);
        menuItem.setAccelerator(KeyStroke.getKeyStroke(
                KeyEvent.VK_2, ActionEvent.ALT_MASK));
        menuItem.addActionListener(this);
        submenu.add(menuItem);

        menuItem = new JMenuItem(PUSTY);
        menuItem.setMnemonic(KeyEvent.VK_S);
        menuItem.addActionListener(this);
        submenu.add(menuItem);

        menu.add(submenu);

        menu = new JMenu("Inne Menu");
        menu.setMnemonic(KeyEvent.VK_I);
        menuBar.add(menu);

        return menuBar;
    }

    public Container createContentPane() {

        card1.init();

        card2.init();

        cards = new JPanel(new CardLayout());
        cards.add(card0, PUSTY);
        cards.add(card1, PRODUKT);
        cards.add(card2, PRODUKTY);

        JPanel p1 = new JPanel();
        p1.add(cards, BorderLayout.CENTER);
        return p1;
    }

    public static void updateProdukty_form() {
        card2.table_content();

        cl.show(cards, PRODUKTY);

    }

    @Override
    public void actionPerformed(ActionEvent e) {

        JMenuItem source = (JMenuItem) (e.getSource());
        //   CardLayout cl = (CardLayout) (cards.getLayout());
        cl = (CardLayout) (cards.getLayout());
        switch (source.getText()) {
            case PRODUKT:
                cl.show(cards, PRODUKT);
                break;
            case PRODUKTY:
                updateProdukty_form();
                break;
            case PUSTY:
                cl.show(cards, PUSTY);
                break;
            default:
                break;
        }
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("MenuDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(900, 400);
        GUI_main demo = new GUI_main();
        frame.setJMenuBar(demo.createMenuBar());
        frame.setContentPane(demo.createContentPane());
        frame.setVisible(true);

    }
      public static void main(String[] args) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }

}


text:
Q: Excel Formula Help Conditional Formatting - If A2 =TODAY and B2=Y turn A2 Green. If B2 = N turn A2 RED Just after some help to make a formula based on two formulas having certain conditions to highlight a Green or Red outcome. It will depend on the TODAY() and turn A2 Green or Red depending if B2 is Y/N.
Thanks in advance.

A: Create a conditional format rule on A2 which says:
=AND(A2=TODAY(),B2="Y")

If both of A2 equals today, and B2 equals "Y", then this will say TRUE. When a conditional formatting rule says TRUE, the rule applies. So, make your rule here highlight Green. Put the normal highlighting as Red, and then the Red will be overridden if the conditional format applies.


text:
Q: Move a label in XAML all I'm trying to do is move a label from one position to another, but when I use the following code and run the application, the IDE tells me that the application went into break mode and then stopped.
The following code is all I have inside the Grid, there is nothing else there and the .cs file is clean (only the constructor with the initializeComponents).
I am using Blend from Visual Studio 2017 Enterprise Edition
<Label x:Name="labelTitle" Foreground="White" FontSize="36" FontWeight="Bold"  HorizontalAlignment="Center" VerticalAlignment="Center" HorizontalContentAlignment="Center" VerticalContentAlignment="Center">
        <Label.Triggers>
            <EventTrigger RoutedEvent="Label.Loaded">
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation
                            Storyboard.TargetName="labelTitle"
                            Storyboard.TargetProperty="(Canvas.Top)"
                            To="500" Duration="0:0:10" />
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Label.Triggers>
        Welcome
    </Label>

Please help me, I don't know what is wrong

A: NaN error is coming above code. To remove NaN error add "From" and "To" in Double animation in above code.
     From="100" To="500" Duration="0:0:10"
Also change Foreground="Black" in labelTitle, So the label will be visible.


text:
Q: jquery validation - show error icon next to control and error summary on top I am interesting in using Jquery Validation in the app (ASP.NET) I am currently developing.
Using the default settings in JQuery really messes up the layout of the form. I wanted to show the error summary on the top of the form and have a icon floating next to the control to indicate the error input.
I know how to get the error summary on the top of the form but not sure how to display the icon next to the control.
I am not even sure if its possible to do both at the same time.
Thanks

A: You can add a handler to the validation plugin as an option:
$("#form").validate({
  errorPlacement: function(error, element) {
    error.wrap("

").appendTo($("#top"));
    $('

').insertAfter(element);
  }
});

.errors { color: red; }
.errorIcon { background: url(errorIcon.png); width: 16px; height: 16px; float: right; }

This appends the error to a element with ID "top" and adds a floating error beside the element that threw the error.  Hopefully this is the idea you're after, if not follow-up with a comment and I'll revise.

A: I have posted a blog post here that explains how to go about doing this from beginning to end for both client and server side validation.  Hope it helps!

A: Consider using native ASP.NET validation instead: RequiredFieldValidator, RegularExpressionValidator, RangeValidator etc. There is also ValidationSummary control. These controls can emit JavaScript code that would do client-side validation (simply set EnableClientScript attribute to true).
Another benefit of ASP.NET validators is that you also get server-side validation - this is critical for public-faced websites.


text:
Q: what are the local-service="true" remote-service="false" in service.xml Can anyone please elaborate what are the local-service="true" remote-service="false" parameters in service.xml.

A: Below is brief detail from liferay-service-builder_6_1_0.dtd.
If the local-service value is true, then the service will generate the local
interfaces for the service. The default value is false.
If the remote-service value is true, then the service will generate remote
interfaces for the service. The default value is true.
You can also refer to link

A: local-service="true"
This will create classes to access your services within the same JVM.
remote-service="true"
This will create classes to access your services from outside.
In your case (local=true;remote=false) - you will be able to call the services in your portlet (or the whole portal, depends on how you set them up), but won't be able to call them from  outside (for example from some SOAP client or a mobile application, etc).


text:
Q: Resource.Load doesn't load latest files in Unity I'm using Resource.Load to load images of screenshots taken within the game. The player takes a picture (screenshot) which is saved as a png file, this image is then loaded into a GUI box and displayed on screen and can be changed to the next or previous image with the right and left arrows. The images that load into the GUI box though are only ones that exist within the Resources folder before the game is run. This means players can only view images from their last play session and not the current one. I was hoping for some insight as to how to fix the error as I have no idea what's causing it. Any help would be appreciated, code posted below:
Screenshot code:
void SavePNG()
{
    Debug.Log("Start Capture");
    picCount += 1;

    var width = Screen.width;
    var height = Screen.height;

    Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);

    RenderTexture rt = new RenderTexture(width, height, 24);
    cam2.targetTexture = rt;
    cam2.Render();
    RenderTexture.active = rt;

    // Read pixels
    tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);

    // Clean up
    cam2.enabled = false;
    cam2.targetTexture = null;
    RenderTexture.active = null; // added to avoid errors
    DestroyImmediate(rt);

    var bytes = tex.EncodeToPNG();
    Destroy (tex);

    File.WriteAllBytes(Application.dataPath + "/../Assets/Resources/" + picCount + ".png", bytes);

    Debug.Log("Captured");
    Debug.Log("Pic Count: " + picCount);
}

GUI Code:
public class UserInterface : MonoBehaviour
{
    public Texture ghostPic;

    private int photoList;
    private int photoNum;
    private string photoString;

    int picHeight;
    int picWidth;

    void Start()
    {
        photoNum = Screenshot.picCount;
        photoList = 0;

        picHeight = Screen.height - 160;
        picWidth = 10;
    }

    void Update()
    {
        photoNum = Screenshot.picCount;

        if(Input.GetButtonDown("Next") && photoNum > 0)
        {
            //Debug.Log("Next");
            photoList++;

            if(photoList == photoNum + 1)
            {
                photoList = 1;
            }

            Debug.Log("Photo List: " + photoList);

            ChangeImage();
        }

        if(Input.GetButtonDown("Last"))
        {
            //Debug.Log("Last");
            photoList--;

            if(photoList == 0)
            {
                photoList = photoNum;
            }

            Debug.Log("Photo List: " + photoList);

            ChangeImage();
        }
    }

    void ChangeImage()
    {
        photoString = photoList.ToString();
        ghostPic = Resources.Load(photoString) as Texture;
    }

    void OnGUI()
    {
        GUI.Box(new Rect(picWidth, picHeight, 300, 150), ghostPic);
    }
}

Thanks for your time :)
ETA:
Ok, so now I'm using Environment.GetFolderPath(Environment.SpecialFolder.Personal)
to access My Documents. I've tried to write that to a string variable but not sure if that's correct:
url = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
But the issue now is that the images are no longer saving to file or loading from file. I've included the new code but it looks like the ChangeImage() function isn't running in the image loader and I have no idea why:
void Start()
    {
        url = Environment.GetFolderPath(Environment.SpecialFolder.Personal);

        photoNum = Screenshot.picCount;
        photoList = 0;

        picHeight = Screen.height - 160;
        picWidth = 10;

        photoString = "0";

        ChangeImage();
    }

    void Update()
    {
        photoNum = Screenshot.picCount;

        if(Input.GetButtonDown("Next") && photoNum > 0)
        {
            Debug.Log("Next");
            photoList++;

            if(photoList == photoNum + 1)
            {
                photoList = 1;
            }

            ChangeImage();
        }

        if(Input.GetButtonDown("Last"))
        {
            Debug.Log("Last");
            photoList--;

            if(photoList <= 0)
            {
                photoList = photoNum;
            }

            ChangeImage();
        }

    }

    void ChangeImage()
    {

        photoString = photoList.ToString();
        WWW www = new WWW(url + photoString);

        WaitForLoad();

        if (isDone)
        {
            www.LoadImageIntoTexture(ghostPic);
            Debug.Log("Photo List: " + photoList);
            Debug.Log("Photo String: " + photoString);

            isDone = false;
        }
    }

    IEnumerator WaitForLoad()
    {
        yield return new WaitForFixedUpdate();

        isDone = true;
    }

    void OnGUI()
    {
        GUI.Box(new Rect(picWidth, picHeight, 300, 150), ghostPic);
    }

I am also using Environment.GetFolderPath(Environment.SpecialFolder.Personal
to save images. Code is same as above with the addition of Environment.Get... etc. and line 28 is now:
File.WriteAllBytes(url + picCount + ".png", bytes);

I'm assuming I've used this incorrectly but I'm not quite sure how. Can anyone point me in the right direction?

A: All assets stored in a folder named Resources are packed into a single file on build.
That means that Resources.Load() requires a path relative to the Resources folder to load the resource, and that the asset name is unique for any other asset in any other Resource folder.

A: The problem is here:
url = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
[...]
WWW www = new WWW(url + photoString);

WWW requires an URI (e.g. file://home/user/) , where Environment.GetFolderPath returns a file system path (e.g. /home/user).
So
WWW www = new WWW("file://" + url + photoString);

should do the trick. Unless you're on Windows, in which case you would need to do:
WWW www = new WWW("file:///" + url + photoString);

(Note the three slashes instead of two)
See:
http://docs.unity3d.com/ScriptReference/WWW.html


text:
Q: Asp.net Web api The requested resource does not support http method 'GET' I want to build a Web API which accepts a string parameter and return a string value,but I always get the error, The requested resource does not support HTTP method GET. I searched a bit in the stack overflow and added the line [AcceptVerbs("GET")] but I still got the error. Could any one help me out?
Global.asax.cs file
 config.Routes.MapHttpRoute(
                name: "sasRoute",
                routeTemplate: "api/sas/{container}",
                defaults: new
                {
                    controller = "sas",
                    container = RouteParameter.Optional
                }
            );

Controller's method
[Route("{container}")]
[AcceptVerbs("GET")]
[HttpGet]
public string GetContainerToken(string container)
{
    return container;
}

A: You do not need to register Custom Route, as you already have Attribute Route.
Remove it from your code. Instead, you will need RoutePrefix.
[RoutePrefix("api/sas")]
public class SasController : ApiController
{
    [Route("{container}")]
    public string Get(string container)
    {
        return container;
    }
}


text:
Q: How to modify list to make identical to different list in Python So I am trying to make two lists identical by making changes to just one of them.
For example, if L1 = [1, 2, 4, 5] and L2 = [1, 3, 4, 5, 6], I would like to remove 2 and add 3 and 6 to L1, making it into [1, 3, 4, 5, 6] as well.
I know how to get a new list with the duplicates/differences, by iterating through them at the same time and compare elements with != but I have no idea how to start on making L1 into L2 by adding/deleting accordingly.
Can anyone help with this? I'm using python btw.

A: Have you tried using pop(). You just say for example:
f l1 == [1, 2, 3, 4, 5, 6] and L2 == [1, 2, 3, 4, 5, 6]:
    l1.pop(3, 4, 7)
    L2.pop(3, 4, 7)
and just to check it you print l1 and L2. But I will explain the pop function.
In the parenthesis you type the index of your number that you want to delete. Don't forget that the count of objects in your list starts from 0.

A: Try this way -
A={1, 2, 4, 5}
B= {1, 3, 4, 5, 6}
C=A&B
C
Out[35]: {1, 4, 5}
B-C
Out[36]: {3, 6}
C=C|(B-C)
C
Out[38]: {1, 3, 4, 5, 6}
A=C
A
Out[40]: {1, 3, 4, 5, 6}

A: You can use list comprehension:
L1 = [1, 2, 4, 5]
L2 = [1, 3, 4, 5, 6]
L1 = [i for i in L2]
print(L1)


text:
Q: collection.find that doesn't match any elements in an array I'm trying to avoid having to use another loop to weed out workers who's ID is in my workersThatApplied array. Is there a way to accomplish this in my query?
  workersThatApplied = ['ehslj8373d', 'gkjhgjr737d'];

  Workers.find({
    'userId: // only select workers who's id isn't in the workersThatApplied array
    'Trades': {$exists: true},
  })

A: Use the mongodb not-in $nin operator:
const workersThatApplied = ['ehslj8373d', 'gkjhgjr737d'];
Workers.find({
  userId: { $nin: workersThatApplied },
  Trades: { $exists: true },
});


text:
Q: Setting Visibility of Datagrid rows to Collapsed seems to break scrollbar? I have a Datagrid containing items as List, one property in this custom list is a bool which determines visibility (the visibility can be toggled by a checkbox).
I have that working as this:
<Style x:Key="RowStyle" TargetType="DataGridRow">
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=IsVisible}" Value="False">
            <Setter Property="Visibility" Value="Collapsed"/>
        </DataTrigger>
        <DataTrigger Binding="{Binding Path=IsVisible}" Value="True">
            <Setter Property="Visibility" Value="Visible"/>
        </DataTrigger>
    </Style.Triggers>
</Style>

And my Datagrid is like:
<DataGrid Name="dataList" DataContext="{StaticResource DataViewSource}" ItemsSource="{Binding}"
          ItemContainerStyle="{StaticResource RowStyle}"
          ScrollViewer.VerticalScrollBarVisibility="Auto"
          ScrollViewer.HorizontalScrollBarVisibility="Auto"
          AutoGenerateColumns="False"
          CanUserAddRows="False"
          CanUserDeleteRows="False"
          IsReadOnly="True"
          CanUserReorderColumns="True" CanUserSortColumns="True"> ..etc

Assume I have 100 rows and when toggling the visibility, 80 of those rows are collapsed.
The issue is: the scrollbar doesn't seem to update when the visibility of items is changed. In appearance it will look as if those 80 rows are still visible (small drag bar) but when trying to scroll through the 20 items that are visible, it requires a lot more scrolling because the scrollbar is assuming that it's still having to scroll through 100 items or something.
Is there a way I can inform the scrollbar of visibility changes? Or should I handle the scroll event myself and remove the scrollbar from the datagrid?

A: The Datagrid uses something called row virtualization by default. When row virtualization is enabled, the scrollbar uses logical scoll units (items) instead of the real size.
Because your collection still contains all items, the scrollbar size does not change.
Solution:
Use the Filter event of the CollectionViewSource instead of binding to the Items viewmodel. MSDN


text:
Q: express/mongodb: Value not entering the database through $push I'm trying to push a value to mongodb when a route is accessed. When i try it pushing through Mongo Shell, the value is pushed, but when i go to the route, nothing is pushed. The route is something like this

router.post('/course/:userid/step-four/:courseid', function(req, res) {
      Course.findOne({
            "_id": req.params.courseid
          }, function(err, course) {
            if (err) {
              res.send(err);
            } else {
              User.update({
                "_id": ObjectId(req.params.userid)
              }, {
                $push: {
                  courseId: req.params.courseid
                }
              });

Note that i'm able to retrieve both url params when i log them in console, but somehow it is not entering into the db. What can i do?


text:
Q: Constructor ClipData.Item is undefined Android im trying to create a item for a list, to display on a listview some pictures.
The codes is the following:
public static List<Item> getItemList(List<Picture> pictures, Context context)
    {
        List <Item> items = new ArrayList<Item>();
        for (int i = 0; i < pictures.size(); i++) {
            Item item = new Item(pictures.get(i).getID(),pictures.get(i).getAddress(),pictures.get(i).getDescription(),pictures.get(i).getPath());
            items.add(item);
        }
        return items;
    }

What i'm trying to do in this is to create an item for each picture on database. (getDescription would be to get the picture description from a database handler, same for address and path)
However im getting the following error in the line where i use the "gets"
The constructor ClipData.Item(int, String, String, String) is undefined.
What could this be? Thank you!
Picture Class
public class Picture {
int _id;
String _name;
String _address;
String _description;
String _path;

// Empty constructor
public Picture(){

}
// constructor
public Picture(int id, String name, String _address, String _description, String _path){
    this._id = id;
    this._name = name;
    this._address = _address;
    this._description = _description;
    this._path = _path;
}

// constructor
public Picture(String name, String _address, String _description){
    this._name = name;
    this._address = _address;
    this._description = _description;
    this._path = _path;
}
// getting ID
public int getID(){
    return this._id;
}

// setting id
public void setID(int id){
    this._id = id;
}

// getting name
public String getName(){
    return this._name;
}

// setting name
public void setName(String name){
    this._name = name;
}

public void setDescription(String description){
    this._description = description;
}

public String getDescription(){
    return this._description;
}

// getting phone number
public String getAddress(){
    return this._address;
}

// setting phone number
public void setAddress(String phone_number){
    this._address = phone_number;
}

public String getPath(){
    return this._path;
}

public void setPath(String path){
    this._path = path;
}

}

A: try to use for each loop
public static List<Item> getItemList(List<Picture> pictures, Context context)
    {
        List <Item> items = new ArrayList<Item>();
        for (Picture pic:pictures) {
            int id = pic.getID();
            String address = pic.getAddress();
            String desc= pic.getDescription();
            String path= pic.getPath();
             Item item = new Item(id ,address ,desc,path);
             items.add(item);
         }
        return items;
    }


text:
Q: Set the legend in a plot to have the name of a column in bokeh Here is my code below, how can I make the legend take the name of the column in rf.index[0].
Simply passing rf.index[0] to legend creates a legend of the categories rather than the actual name of the column.
p1.line(
    x = 'x',
    y = rf.index[0],
    source=source,
    legend = ???,
    color = 'black'

)

A: Here is the answer!
legend = dict(value=rf.index[0])

source
https://github.com/bokeh/bokeh/issues/5365


text:
Q: Search in API and Display API How to search that any keywords
I have two different blocks of code but I dont know how i can combine it
The things that i want is when you search in second box it will display like first coding. I dont mind if got button not.

        <title>JSON/Atom Custom Search API Example</title>

            <input type="text" id="Query">
            <button id="add">Search</button>

    <form>
    <input type="text" onkeyup="showHint(this.value)">
    </form>

Answer

For more details
http://mediamonitoring.comyr.com/jquery3.php