text:
Q: Use Angular Cli with Webpack I am trying to incorporate cli generate commands in my angular2 project but it gives me a error
I am using the angular2-webpack-starter from git
You have to be inside an angular-cli project in order to use the generate command.
I did npm install-g angular-cli
also in my package.json there i have added the dependency but it dosent work,how to make it work
My package.json
{
  "name": "angular2-webpack-starter",
  "version": "5.4.1",
  "description": "An Angular 2 Webpack Starter kit featuring Angular 2 (Router, Http, Forms, Services, Tests, E2E, Coverage), Karma, Protractor, Jasmine, Istanbul, TypeScript, and Webpack by AngularClass",
  "keywords": [
    "angular2",
    "webpack",
    "typescript"
  ],
  "author": "Patrick Stapleton <patrick@angularclass.com>",
  "homepage": "https://github.com/angularclass/angular2-webpack-starter",
  "license": "MIT",
  "scripts": {
    "build:aot:prod": "npm run clean:dist && npm run clean:aot && webpack --config config/webpack.prod.js  --progress --profile --bail",
    "build:aot": "npm run build:aot:prod",
    "build:dev": "npm run clean:dist && webpack --config config/webpack.dev.js --progress --profile",
    "build:docker": "npm run build:prod && docker build -t angular2-webpack-start:latest .",
    "build:prod": "npm run clean:dist && webpack --config config/webpack.prod.js  --progress --profile --bail",
    "build": "npm run build:dev",
    "ci:aot": "npm run lint && npm run test && npm run build:aot && npm run e2e",
    "ci:jit": "npm run lint && npm run test && npm run build:prod && npm run e2e",
    "ci:nobuild": "npm run lint && npm test && npm run e2e",
    "ci:testall": "npm run lint && npm run test && npm run build:prod && npm run e2e && npm run build:aot && npm run e2e",
    "ci:travis": "npm run lint && npm run test && npm run build:dev && npm run e2e:travis && npm run build:prod && npm run e2e:travis && npm run build:aot && npm run e2e:travis",
    "ci": "npm run ci:testall",
    "clean:dll": "npm run rimraf -- dll",
    "clean:aot": "npm run rimraf -- compiled",
    "clean:dist": "npm run rimraf -- dist",
    "clean:install": "npm set progress=false && npm install",
    "clean": "npm cache clean && npm run rimraf -- node_modules doc coverage dist compiled dll",
    "docker": "docker",
    "docs": "npm run typedoc -- --options typedoc.json --exclude '**/*.spec.ts' ./src/",
    "e2e:live": "npm-run-all -p -r server:prod:ci protractor:live",
    "e2e:travis": "npm-run-all -p -r server:prod:ci protractor:delay",
    "e2e": "npm-run-all -p -r server:prod:ci protractor",
    "github-deploy:dev": "webpack --config config/webpack.github-deploy.js --progress --profile --env.githubDev",
    "github-deploy:prod": "webpack --config config/webpack.github-deploy.js --progress --profile --env.githubProd",
    "github-deploy": "npm run github-deploy:dev",
    "lint": "npm run tslint \"src/**/*.ts\"",
    "postinstall": "npm run webdriver:update",
    "postversion": "git push && git push --tags",
    "preclean:install": "npm run clean",
    "preversion": "npm test",
    "protractor": "protractor",
    "protractor:delay": "sleep 3 && npm run protractor",
    "protractor:live": "protractor --elementExplorer",
    "rimraf": "rimraf",
    "server:dev:hmr": "npm run server:dev -- --inline --hot",
    "server:dev": "webpack-dev-server --config config/webpack.dev.js --progress --profile --watch --content-base src/",
    "server:prod": "http-server dist -c-1 --cors",
    "server:prod:ci": "http-server dist -p 3000 -c-1 --cors",
    "server": "npm run server:dev",
    "start:hmr": "npm run server:dev:hmr",
    "start": "npm run server:dev",
    "test": "npm run lint && karma start",
    "tslint": "tslint",
    "typedoc": "typedoc",
    "version": "npm run build",
    "watch:dev:hmr": "npm run watch:dev -- --hot",
    "watch:dev": "npm run build:dev -- --watch",
    "watch:prod": "npm run build:prod -- --watch",
    "watch:test": "npm run test -- --auto-watch --no-single-run",
    "watch": "npm run watch:dev",
    "webdriver-manager": "webdriver-manager",
    "webdriver:start": "npm run webdriver-manager start",
    "webdriver:update": "webdriver-manager update",
    "webpack-dev-server": "webpack-dev-server",
    "webpack": "webpack"
  },
  "dependencies": {
    "@angular/common": "~2.4.3",
    "@angular/compiler": "~2.4.3",
    "@angular/compiler-cli": "~2.4.3",
    "@angular/core": "~2.4.3",
    "@angular/forms": "~2.4.3",
    "@angular/http": "~2.4.3",
    "@angular/platform-browser": "~2.4.3",
    "@angular/platform-browser-dynamic": "~2.4.3",
    "@angular/platform-server": "~2.4.3",
    "@angular/router": "~3.4.3",
    "@angularclass/conventions-loader": "^1.0.2",
    "@angularclass/hmr": "~1.2.2",
    "@angularclass/hmr-loader": "~3.0.2",
    "core-js": "^2.4.1",
    "http-server": "^0.9.0",
    "ie-shim": "^0.1.0",
    "jasmine-core": "^2.5.2",
    "reflect-metadata": "^0.1.9",
    "rxjs": "~5.0.2",
    "zone.js": "~0.7.4"
  },
  "devDependencies": {

    "@types/hammerjs": "^2.0.33",
    "@types/jasmine": "^2.2.34",
    "@types/node": "^7.0.0",
    "@types/selenium-webdriver": "~2.53.39",
    "@types/source-map": "^0.5.0",
    "@types/uglify-js": "^2.0.27",
    "@types/webpack": "^2.0.0",
    "add-asset-html-webpack-plugin": "^1.0.2",
    "angular2-template-loader": "^0.6.0",
    "assets-webpack-plugin": "^3.4.0",
    "awesome-typescript-loader": "~3.0.0-beta.18",
    "codelyzer": "~2.0.0-beta.4",
    "copy-webpack-plugin": "^4.0.0",
    "css-loader": "^0.26.0",
    "exports-loader": "^0.6.3",
    "expose-loader": "^0.7.1",
    "extract-text-webpack-plugin": "~2.0.0-beta.4",
    "file-loader": "^0.9.0",
    "find-root": "^1.0.0",
    "gh-pages": "^0.12.0",
    "html-webpack-plugin": "^2.21.0",
    "imports-loader": "^0.7.0",
    "istanbul-instrumenter-loader": "1.2.0",
    "jasmine-core": "^2.5.2",
    "json-loader": "^0.5.4",
    "karma": "^1.2.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-coverage": "^1.1.1",
    "karma-jasmine": "^1.0.2",
    "karma-mocha-reporter": "^2.0.0",
    "karma-remap-coverage": "^0.1.4",
    "karma-sourcemap-loader": "^0.3.7",
    "karma-webpack": "2.0.1",
    "ng-router-loader": "^1.0.2",
    "ngc-webpack": "1.1.0",
    "node-sass": "^4.2.0",
    "npm-run-all": "^4.0.0",
    "parse5": "^3.0.1",
    "protractor": "^4.0.14",
    "raw-loader": "0.5.1",
    "rimraf": "~2.5.4",
    "sass-loader": "^4.1.1",
    "script-ext-html-webpack-plugin": "^1.3.2",
    "source-map-loader": "^0.1.5",
    "string-replace-loader": "1.0.5",
    "style-loader": "^0.13.1",
    "to-string-loader": "^1.1.4",
    "ts-helpers": "1.1.2",
    "ts-node": "^2.0.0",
    "tslint": "~4.3.1",
    "typedoc": "^0.5.3",
    "typescript": "~2.1.5",
    "url-loader": "^0.5.7",
    "v8-lazy-parse-webpack-plugin": "^0.3.0",
    "webpack": "2.2.0",
    "webpack-dev-middleware": "^1.9.0",
    "webpack-dev-server": "2.2.0",
    "webpack-dll-bundles-plugin": "^1.0.0-beta.5",
    "webpack-md5-hash": "^0.0.5",
    "webpack-merge": "~2.4.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/angularclass/angular2-webpack-starter.git"
  },
  "bugs": {
    "url": "https://github.com/angularclass/angular2-webpack-starter/issues"
  },
  "engines": {
    "node": ">= 4.2.1",
    "npm": ">= 3"
  }
}

A: You can't combine angular2-webpack-starter and angular-cli.
To be able to use angular-cli, you must initialize your project with it:
ng new PROJECT_NAME


text:
Q: Add URL to slider with Custom Field in WordPress I'm trying to add a url to each slide, via a custom field I created.
This was already in the code:
            <img src="<?php echo bfi_timthumber($largeImage, 980, (int)$sliderHeight)?>" width="980" height="<?php echo $sliderHeight ?>" title="#nivocaption<?php echo $i?>"/>

So I thought if I created the custom field I could just wrap it in this:
 <a href="<?php echo get_post_meta($post->ID, 'slide_url', true); ?>"> ABOVE CODE HERE

But unfortunately that isn't working. Any thoughts to why?
Here is the full code: http://pastebin.com/yNzk8izb

A: well - I do not know your theme / plugin , but the
$lardeImage parameter is the one you probably need to use .
Wraping it like you did will obviously make it double, because you are not over riding the code, you just add to it .
try :
$largeImage = get_post_meta($post->ID, 'slide_url', true);

and then the code .
Note :
(it might not work, because like i said - i do not know the plugin / theme function - but the $LargeImage parameter name sugests it needs to take only the "FULL" image size .. )
But try it anyhow .

redpajama_set_name: RedPajamaStackExchange


text:
Q: JavaScript/React - Update a value in array with particular key name from a array of arrays In the below array of arrays I need to update the id value for a particular name.
objArray = [{ name: John, id: 12}, { name: Jake, id: 45}, { name: Jacob, id: 78}];

Ex: If user enters a name and id in text boxes and clicks submit I want to update the id in the array for the particular name.
I can accomplish this using for loops but can you please let me know the most efficient way to do this in Java Script/React?

A: Use the find function and set the entered name.
Look at this code snippet

let objArray = [{  name: "John",  id: 12}, {  name: "Jake",  id: 45}, {  name: "Jacob",  id: 78}];

let name = 'Jake'
let newId = 59;
objArray.find((o) => o.name === name).id = newId;

console.log(objArray);
.as-console-wrapper {
  max-height: 100% !important
}

A: You can use findIndex to get the index of the object whose name matches. Then use that index to update the id

var objArray = [{
  name: 'John',
  id: 12
}, {
  name: 'Jake',
  id: 45
}, {
  name: 'Jacob',
  id: 78
}];

function update() {
  var getVal = document.getElementById('ip').value.trim();
  var getIndex = objArray.findIndex(function(item) {
    return item.name.toLowerCase() === getVal.toLowerCase();
  })
  objArray[getIndex].id= "newId"
  console.log(objArray)
}
<input type="text" id="ip">
<button onclick="update()">Update</button>


text:
Q: Nested movieclip rotation doesn't work if parent rotates too I have a tank which has a nested movieclip called Barrel.
Barrel successfully faces the player, unless the tank itself rotates.
So it only works if the tank doesn't rotate.
I need to find a way to make the rotation work, and I googled and found:
var rot:Number = rotation, p:DisplayObjectContainer = parent, s:DisplayObjectContainer =     stage;
while (p != s) {
  rot += p.rotation;
  p = p.parent;
}

But I have no idea how to implement this in my current code:
// calculate rotation based on target

            _dx = this.x - _root.hero.x;
            _dy = this.y - _root.hero.y;

// which way to rotate

            _rotateTo = getDegrees(getRadians(_dx, _dy));

// keep rotation positive, between 0 and 360 degrees

            if (_rotateTo > barrel.rotation + 90) _rotateTo -= 360;
            if (_rotateTo < barrel.rotation - 90) _rotateTo += 360;

// ease rotation

            _trueRotation = (_rotateTo - barrel.rotation) /     _rotateSpeedMax;

//barrel rotation

            barrel.rotation += _trueRotation;

I tried changing
barrel.rotation += _trueRotation;

to
barrel.rotation += _trueRotation + parent.rotation

after reading online that you can simply add all the rotations, but it doesn't seem to work.
How can I implement
var rot:Number = rotation, p:DisplayObjectContainer = parent, s:DisplayObjectContainer =         stage;
while (p != s) {
  rot += p.rotation;
  p = p.parent;
}

into my code?

A: You have to negate the rotation of parent(s), thus you just change += to -=, should do.
 rot -= p.rotation;


text:
Q: ActiveRecord + Pry confusion This is confusing me no end.
In a rake task, I am saving new records on the DailyScore model with the following code:
def save_record_as_daily_score_object(data)
    @ds = DailyScore.where(date: data[:date]).first_or_create!
    @ds.update!(data)
    binding.pry
end

The pry output is as follows:
[10] pry(main)> data
=> {:date=>"2015-09-02",
:mail=>-0.6,
:times=>-7.1,
:telegraph=>-2.2,
:guardian=>-4.0,
:express=>-0.1,
:independent=>-3.2,
:average=>-3.4}

[11] pry(main)> @ds
=> #<DailyScore:0x000001098121a8
 id: 4975,
 mail: nil,
 telegraph: nil,
 times: nil,
 average: nil,
 guardian: nil,
 independent: nil,
 express: nil,
 date: nil,
 created_at: 2016-05-16 13:10:03 UTC,
 updated_at: 2016-05-16 13:10:03 UTC>

 [12] pry(main)> @ds.average
 => -3.4
 [13] pry(main)> @ds.date
  => "2015-09-02"
 [14] pry(main)> @ds.persisted?
  => true
 [15] pry(main)> DailyScore.last
=> #<DailyScore:0x000001086810d8
 id: 4975,
 mail: nil,
 telegraph: nil,
 times: nil,
 average: nil,
 guardian: nil,
 independent: nil,
 express: nil,
 date: nil,
 created_at: 2016-05-16 13:10:03 UTC,
 updated_at: 2016-05-16 13:10:03 UTC>
 [16] pry(main)> DailyScore.last.average
=> nil

What is going on here? Why can't Pry access my variable attributes? And is the record actually being saved or not?
UPDATE:
Checking in the console, the behaviour is the same if I simply create a new object. I'm using the Padrino framework, and a Postgres db.
2.0.0 :001 > ds = DailyScore.new(date:"2016-01-01")
 => #<DailyScore id: nil, mail: nil, telegraph: nil, times: nil, average: nil, guardian: nil, independent: nil, express: nil, date: nil, created_at: nil, updated_at: nil>
2.0.0 :002 > ds.date
 => "2016-01-01"
2.0.0 :003 > ds
 => #<DailyScore id: nil, mail: nil, telegraph: nil, times: nil, average: nil, guardian: nil, independent: nil, express: nil, date: nil, created_at: nil, updated_at: nil>

Is it a problem with the model? Here is the original migration:
006_create_daily_scores.rb
class CreateDailyScores < ActiveRecord::Migration
   def self.up
     create_table :daily_scores do |t|
       t.float :average
       t.datetime :date
       t.float :express
       t.float :independent
       t.float :guardian
       t.float :telegraph
       t.float :mail
       t.float :times
       t.timestamps
     end
   end

   def self.down
     drop_table :daily_scores
   end
 end

Have now added another column day:date - using :date instead of :datetime - to check if it was a quirk with :datetime, but behaviour is the same.

A: This happens because you called attr_accessor in your model with your model attributes, which overrode default accessors provided by Rails (the accessors are called by update and new methods). Note this doc, for reference, if you do want to override accessors one day.
Removing attr_accessor from your model will do the trick!


text:
Q: Using keyboard interrupt to display something different than what the user typed In the C language, using keyboard interrupt, how can I display an alternate key from what the user typed? E.g., when I press 'Q' on the keyboard, then the screen should display 'A'.

A: Handling keyboard interrupt is not a good idea on any platform.
What about usb keyboards, there is no interrupt you can catch ?
For Windows OS's you probably want to write filter driver, you can find this replay partly relevant.
Sample of keyboard filter driver can be found here.
For Linux you probably need to patch HID layer driver. Mac is out my scope completely :)

A: We need a little more information about Your environment.
As far as I understand Your question, You want to replace the
keyboard interrupt handler with Your own in this way:

*

*Save the entry address of the original keyboard handler.

*Install Your own that calls the original and manipulates the keycode value.

However, on most modern operating systems it is much easier to define and install a new keyboard layout.


text:
Q: Difference between fragmentTransaction.hide and setVisibility(GONE); Is there any principal difference between setting layout's visibility that contains fragment to GONE and fragmentTransaction.hide(fragment) apart from addToBackStack ?

A: fragmentTransaction.hide(fragment) does
public void hideFragment(Fragment fragment, int transition, int transitionStyle) {
    if (DEBUG) Log.v(TAG, "hide: " + fragment);
    if (!fragment.mHidden) {
        fragment.mHidden = true;
        if (fragment.mView != null) {
            Animator anim = loadAnimator(fragment, transition, true,
                    transitionStyle);
            if (anim != null) {
                anim.setTarget(fragment.mView);
                // Delay the actual hide operation until the animation finishes, otherwise
                // the fragment will just immediately disappear
                final Fragment finalFragment = fragment;
                anim.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        if (finalFragment.mView != null) {
                            finalFragment.mView.setVisibility(View.GONE);
                        }
                    }
                });
                anim.start();
            } else {
                fragment.mView.setVisibility(View.GONE);
            }
        }
        if (fragment.mAdded && fragment.mHasMenu && fragment.mMenuVisible) {
            mNeedMenuInvalidate = true;
        }
        fragment.onHiddenChanged(true);
    }
}

So it does pretty much the same but it

*

*supports animation

*supports backstack

*sets the View returned from Fragment#onCreateView() to GONE instead of the container

*takes care for the menu if you fragment added sth there


text:
Q: Security risk of PHP variables The page I'm building interacts with the java api of another system to retrieve data via the command line. This is triggered from PHP, but needs a valid username and password sent with every call.
I don't want to store the username and password in either a file or a cookie, as I don't believe there's a way of doing so safely. However, I also don't want to make my users enter their credentials multiple times.
What I'm proposing to do is the ask for the username and password once, and store them in global variables in my php, using an include to make sure that all other php files had access to them.
My question is, is it safe to do this or would someone be able to view the state of the variables and discover the username and password?

A: The variables will only be 'set' during the scripts runtime, after the script have ben ran, they will be the value they where set to default.
Ie. If you reload the page, the 'stored data' will be gone.
Take a look at sessions, might be the best solution.

A: You have to use sessions. HTTP is a stateless protocol. If you have multiple requests with multiple clients, and you want to make it stateful (remember who is requesting), you need to use a session-based-solution: Put a session-id in a cookie on your clients system, send this cookie to your application on each request, and find out which data are associated with this session-id.
I know you want to avoid to "store the username and password" in a cookie. But I'm not absolutly sure if you know that in a php-managed session-based solution your session-data are NOT safed in a cookie. They can't be read out throughout the cookie. In fact, only the session-id is saved in the cookie. Your server then manages the reference between the session-id and all data in $_SESSION (which are only saved on the servers side!) - your user can't guess what kind of data is put into his session just because he reads out the cookies value.
The only security risk here is a session hijacking: Another person could try to steal your clients cookie to take over his session. But there are solutions for this scenario, just check them out and you will have a secure session-based solution.
Remember: If it comes to security, always try to prefer proven design patterns over developing your own stuff.


text:
Q: Find the biggest sum from sequence of number which within a range I need help. How do I find the greatest sum from sequence of number within a finite range, for example:
Given sequence {2,5,4,3,6} and the range is 11, so how to find the number within the sequence which the sum is less than or same with 11. ex: 5 and 6.
Note : the result must not greater than the range
Thanks for your help....

A: This is a special case of the knapsack problem in which the value of each item is equal to its weight. It's often called a subset sum problem, but unfortunately the latter term is also used for another problem (finding a subset that sums precisely to a given integer).
The slides by Carl Kingsford,
based on  Section 6.4 of Algorithm Design by Kleinberg & Tardos, give an accessible introduction to this (well-studied) problem, with pseudocode algorithm quoted below. The algorithm considers the two-parameter family of problems $\mathrm{Opt}(j,w)$ which seeks the sum of at most $w$ among the first $j$ integers. If the original problem is $\mathrm{Opt}(n,W)$, the algorithm solves $\mathrm{Opt}(j,w)$ for all $j\le n$ and $w\le W$
SubsetSum(n, W):
Initialize M[0,w] = 0 for each w = 0,...,W
Initialize M[i,0] = 0 for each i = 1,...,n
For i = 1,...,n:
 For w = 0,...,W:
  If w[i] > w:
     M[i,w] = M[i-1,w]
  M[i,w] = max( M[i-1,w], w[j] + M[i-1, W-w[j]] )
Return M[n,W]


text:
Q: Unknown escape sequence I am trying to printf a string that shows a temperature table
printf("TABLE 24A (20\°C)");
The degree sign is a constant I have defined as 0xDF so the the string looks like this: "TABLE 24A (20\xDF C)"
This works but looks incorrect because of the space between the \xDF and the C.
If I remove the space the compiler issues a warning hex escape sequence out of range.
If I modify the string to "TABLE 24A (20\xDF\C)" I get the correct result but the compiler issues warning unknown escape sequence: '\C'
Is there a way to get rid of the warnings but lose the space between the two characters?

A: You can take advantage of the fact that consecutive string literals are automatically concatenated:
 printf("**TABLE 24A (20\xDF" "C)**");

This prevents the parser from consuming more characters for the escape sequence than you want.
You could also pass in the character as a parameter and use the %c format specifier to print it:
printf("**TABLE 24A (20%cC)**", '\xDF');

A: \x escape sequences consume as many adjacent hex digits as possible. The C is being parsed as a hex digit.
With \x, you could combine two adjacent string literals.
printf("**TABLE 24A (20\xDF""C)**");

Or use a \unnnn Unicode escape, which is limited to four hex characters.
printf("**TABLE 24A (20\u00DFC)**");

Or octal \nnn:
printf("**TABLE 24A (20\337C)**");


text:
Q: Updating always encrypted column using synonyms I have the following scenario where I have to update 2 always encrypted columns in a SQL Server stored procedure.

*

*One column is in the current database (insert statement)

*The other column is in another database which is being accessed by a synonym (update statement)

The always encrypted columns' master key is in Azure Keyvault.
The stored procedure is compiling successfully with either insert or the update, but not both.
When I include both the statements in the stored procedure, it fails with the error message:

Encryption scheme mismatch for columns/variables '@variableName'. The encryption scheme for the columns/variables is (encryption_type = 'DETERMINISTIC', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'CEKName', column_encryption_key_database_name = 'DBName') and the expression near line '8' expects it to be DETERMINISTIC, or PLAINTEXT.

Stored procedure code:
ALTER PROCEDURE [dbo].[UserCreatedSPName]
AS
BEGIN
    INSERT INTO Table(columns list)
    VALUES (incoming params)

    UPDATE SynonymTable
    SET AlwaysEncryptedColumn = [@sameincomingvariable as in above insert]
    WHERE [filter condition]
END

Is this something that can be accomplished?
I have tried moving the update statement into a separate stored procedure and calling it from the main stored procedure - but I am still getting the same error.
Update: The Insert and Update are both happening the same Stored procedure. Also the 2 tables have a separate Column Master Keys in Azure key vault

A: I created a table and inserted values into that table and enable always encrypted column in by saving the master key value in azure key vault.
Table before encryption:

After encryption:

I created synonym table for the above table in another database using below code:
CREATE SYNONYM syn_product
FOR [product].[dbo].[DBtable]
GO
select * from syn_product

Image for reference:

I try to insert values into DBtable which is encrypted by creating stored procedure:
Create PROCEDURE [dbo].[product]
   @id int,
   @name VARCHAR(20),
   @price int
AS
BEGIN
   INSERT dbo.DBtable(ID,Name,Price) SELECT @id, @name, @price;
END

Executed the stored procedure.
EXEC  dbo.product @id = 6, @name = 'P6', @price = 100

I got below the below error:

I tried to update the column by using synonym table with below code:
Create PROCEDURE [dbo].[upda]
@id INT, @name VARCHAR (20)
AS
BEGIN
    UPDATE DBtable
    SET    ID = @id
    WHERE  name = @name;
END

Executed the stored procedure.
EXEC upda @id = 6, @name = 'P1'

I got the below error:

I disconnected the server and connected again with
Column Encrypted Setting = Enabled

in additional connection parameters.
Image for reference:

I selected Query Options:

From Advanced -> Check the box 'Enable Parameterization for Always Encrypted'

I tried to insert values in DBTable which in current database using below code:
 declare @id int = 12
declare @Name varchar(20) = 'P6'
declare @price int = 100
insert into DBtable values(@id,@name,@price)

It worked successfully,
Image for reference:

Data of DBtable:

I tried to update the Synonym table using below code:
declare @id int = 6
update syn_product set ID = @id where Name = 'P1'

It worked successfully.
Image fore reference:

Synonym Table data:

In this way we can modify the data in table which is having always encrypted column and its synonym table.
Note: SSMS 17.0 and above has the option to edit the Always Encrypted Column. You can get SSMS 17.1 from [here  ![Jump](https://social.technet.microsoft.com/wiki/cfs-file.ashx/__key/communityserver-components-sitefiles/10_5F00_external.png "This link is external to TechNet Wiki. It will open in a new window.")](https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms) .


text:
Q: Android NDK: Call to System.loadLibrary Results in SIGSEGV Code=1 I have a massive C/C++ library that I'm trying to use through JNI for an Android project.  It's comprised of several classes that were originally written for MFC and we've ported them over for execution on the Android environment.
The library builds fine (at least according to ndk-build). The size of the library is 56 MB in size.
When I call System.loadLibrary, the application terminates with the following being logged:

Fatal Signal 11 (SIGSEGV) at 0x00000004 (Code = 1), thread 16123

I performed an objdump on my library and there is nothing at 0004. Here's the first few lines of the dump :
DYNAMIC SYMBOL TABLE:
00000000      DF *UND*  00000000 __cxa_finalize
002fe600 g    D  .bss   00000000 __dso_handle
002f1e9c g    D  .init_array    00000000 __INIT_ARRAY__
002f20a4 g    D  .fini_array    00000000 __FINI_ARRAY__
0011dc58 g    DF .text  000000ec WideToJava
00000000      DF *UND*  00000000 __android_log_print
0021f460 g    DF .text  00000030 wcslen
00000000      DF *UND*  00000000 malloc
00000000      DF *UND*  00000000 free
0011dd44 g    DF .text  000000e4 WideToJava2
0011de28 g    DF .text  0000004e JavaToWSZ
0027443c g    DF .text  0000001c _Znaj
0011dec4  w   DF .text  00000018

I then performed a readelf to see if there is another library that needs to be loaded, listed here :
Dynamic section at offset 0x2d99e0 contains 28 entries:
  Tag        Type                         Name/Value
 0x00000003 (PLTGOT)                     0x2fe464
 0x00000002 (PLTRELSZ)                   776 (bytes)
 0x00000017 (JMPREL)                     0x11d4a0
 0x00000014 (PLTREL)                     REL
 0x00000011 (REL)                        0x107770
 0x00000012 (RELSZ)                      89392 (bytes)
 0x00000013 (RELENT)                     8 (bytes)
 0x6ffffffa (RELCOUNT)                   11169
 0x00000006 (SYMTAB)                     0x128
 0x0000000b (SYMENT)                     16 (bytes)
 0x00000005 (STRTAB)                     0x31cd8
 0x0000000a (STRSZ)                      791389 (bytes)
 0x00000004 (HASH)                       0xf3038
 0x00000001 (NEEDED)                     Shared library: [liblog.so]
 0x00000001 (NEEDED)                     Shared library: [libandroid.so]
 0x00000001 (NEEDED)                     Shared library: [libstdc++.so]
 0x00000001 (NEEDED)                     Shared library: [libm.so]
 0x00000001 (NEEDED)                     Shared library: [libc.so]
 0x00000001 (NEEDED)                     Shared library: [libdl.so]
 0x0000000e (SONAME)                     Library soname: [libCSEntry.so]
 0x00000019 (INIT_ARRAY)                 0x2f1e9c
 0x0000001b (INIT_ARRAYSZ)               520 (bytes)
 0x0000001a (FINI_ARRAY)                 0x2f20a4
 0x0000001c (FINI_ARRAYSZ)               12 (bytes)
 0x00000016 (TEXTREL)                    0x0
 0x00000010 (SYMBOLIC)                   0x0
 0x0000001e (FLAGS)                      SYMBOLIC TEXTREL
 0x00000000 (NULL)                       0x0

Then I added those libraries before my call to loadLibrary :
public class ApplicationInterface
{
 static
 {
  System.loadLibrary("log");
  System.loadLibrary("android");
  System.loadLibrary("stdc++");
  System.loadLibrary("m");
  System.loadLibrary("c");
  System.loadLibrary("dl");
  // when i call load library it blows up
  System.loadLibrary("CSEntry");
 }
// code
}

What's stranger is that there is a specific class that blows up this code.  When I commented out the constructor to this class the library loads fine.  I've verified that the constructor exists in the resulting library using objdump.  I then proceeded to comment out the code in the constructor and it fails as well.  Here's the offending code in the C++:
// Code
m_pPifFile = new CNPifFile(sPifFilePath);

m_pPifFile->SetAppType(ENTRY_TYPE);
m_pPifFile->SetAppFName(sApplicationFilename);
m_pPifFile->SetBinaryLoad(true);

// load the PIF file
if(m_pPifFile->LoadPifFile())
{
    // PIF file loaded create a new Run App
    // the offending line
    m_pRunAplEntry = new CRunAplEntry(m_pPifFile);
// Code

RunAplEntry.h
class AFX_EXT_CLASS CRunAplEntry : public CRunApl
{
public:
    CRunAplEntry(CNPifFile* pPifFile);
    ~CRunAplEntry();

// code
};

RunApl.h
class CLASS_DECL_ZBRIDGEO CRunApl : public CObject
{
public:
    CRunApl();
    virtual ~CRunApl();
// code
};

AFX_EXT_CLASS and CLASS_DECL_ZBRIDGEO are #defined to empty space.
We wrote a CObject equivalient for the Android NDK.
Here are the makefiles :
Application.mk
# set the platform to the latest processor type
APP_ABI                 := armeabi-v7a
# build for GNU STL
APP_STL                 := gnustl_static
# turn on exceptions and runtime type info
APP_CPPFLAGS            += -fexceptions -frtti

Android.mk
LOCAL_LDLIBS            := -llog -landroid $(BOOST_LIBS) -lgnustl_static
LOCAL_LDFLAGS           := -L$(BOOST_PATH)/lib/arm
LOCAL_CFLAGS            := -D__GLIBC__=1
LOCAL_CFLAGS            += -D_GLIBCXX_USE_C99_MATH=1
LOCAL_CFLAGS            += -DUNICODE=1
LOCAL_CFLAGS            += -D_UNICODE=1
LOCAL_CFLAGS            += -DGENERATE_BINARY=1
LOCAL_CFLAGS            += -DUSE_BINARY=1
LOCAL_CFLAGS            += -DPORTABLE=1
LOCAL_CFLAGS            += -fpermissive
LOCAL_CFLAGS            += $(CSPROMOBILE_INCLUDE)
LOCAL_STATIC_LIBRARIES  := Engine zTbdO zFormO zDictO zToolsO zUtilO zCommonO

I've noticed that the GCC compiler doesn't handle virtual functions very well and I suspect this could be the problem, but I'm not sure.  Here are the details for my environment.
NDK: Crystax r75
ABI Target: 4.6.3
ADT: v21.0.1-543035
Debug Device: Nexus 7
Any help will be greatly appreciated.
If you have any additional info please don't hesitate to ask.
Thanks,
Will


text:
Q: How to verify correct operation of Hibernate second level caching in a cluster? I am wondering how to verify that Hibernate's L2 cache performs correctly. I have an application running on a cluster of JBoss 5 instances with JBoss Cache. Load testing would answer the question of performance.
But how to make sure that cluster related issues like the cache invalidation between nodes works like it should be?

A: I would suggest requesting resources by IP address.  On server A, you can perform an update, and then request that same resource from server B.  On update the resource should be invalidated from participating servers in the cluster, so the resulting request on server B should be the (newly) updated resource.

A: The easiest would be to check the 2nd level cache contents via the embedded console that JBoss 5 comes with and do an exercise like the one @Rich Kroll suggests.
You can have a look at the Cache statistics via the embedded console that JBoss 5 comes with. It'll show the number of invalidations that have happened.


text:
Q: Install Ubuntu to Boot from Partition on external Hard Drive How might I partition my hard drive so that I can boot Ubuntu from one partition and file storage in another. I am running Mac OSX Mountain Lion. I want to boot from my external Hard Drive into Ubuntu on a mac computer. My external Hard Drive is dual USB connected.

A: Appropriately partition your external drive. Create a Ubuntu live CD/USB and boot from it. When it prompts you to choose your install method, click "Something else."
It will take you to a menu to choose the disk you want to install on. Choose your external drive, and create one partition that is >= the amount of physical RAM you have installed in your Mac, and format it as Swap. Then, format the remaining as ext4. Set the ext4 mount point to /.
Select the ext4 partition, and click install. Ubuntu will install on the selected partition. Follow prompts to set up your user account, password, and basically general things.
After Ubuntu is installed, it will prompt for reboot. Reboot, and as your Mac starts back up, hold the option/alt key and it will open up the boot menu. Select your hard drive partition, and boot into Ubuntu.
Enjoy :)


text:
Q: Как правильно внести значение просмотров в лист тренируюсь в написании html парсера суть работы в том что бы вытащить с сайта инфу о сериалах а именно Названия / URL постера / Просмотры, с названием и URL постера все прошло гладко но на просмотрах у меня всё встало не получается занести их в список.
сделал как смог, но все просмотры съехали на одну позицию вниз, как можно поправить?

using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleSimpleHTMLParser
{
    #region
    // Базовый класс, в котором храняться название тайтла, ссылки на постер и колличество просмотров.
    class SeriesData
    {
        public SeriesData(string t, string up, string v)
        {
            Title = t;
            UrlPoster = up;
            View = v;
        }
        public string Title { get; set; }
        public string UrlPoster { get; set; }
        public string View { get; set; }
    }

    class Series : SeriesData
    {
        public Series(string t, string up, string v) : base(t, up, v)
        {
            // ...
        }
    }

    // Класс SeriesList способен управлять любым видом списков сериалов.
    // при условии, что он является производным от класса SeriesData.
    class SeriesList<T> where T : SeriesData
    {
        T[] serList;
        int end;

        public SeriesList()
        {
            serList = new T[10000];
            end = 0;
        }

        // Добавить элемент в список.
        public bool Add(T newEntry)
        {
            if (end == 10000)
            {
                return false;
            }

            serList[end] = newEntry;
            end++;
            return true;
        }

        public void Insert(string inst, int count)
        {
            try
            {
                serList[count].View = inst;
            }
            catch (Exception exc)
            {
                count--;
                serList[count].View = inst;
            }
        }

        public void ShowList()
        {
            for (int i = 0; i < end; i++)
            {
                Console.WriteLine("Название: {0} \nURL Постера: {1}\nПросмотры: {2}\n", serList[i].Title, serList[i].UrlPoster, serList[i].View);
            }
        }
    }
    #endregion

    class Program
    {
        static string LoadPage(string url)
        {
            var result = "";
            var request = (HttpWebRequest)WebRequest.Create(url);
            var response = (HttpWebResponse)request.GetResponse();

            if (response.StatusCode == HttpStatusCode.OK)
            {
                var receiveStream = response.GetResponseStream();
                if (receiveStream != null)
                {
                    StreamReader readStream;
                    if (response.CharacterSet == null)
                        readStream = new StreamReader(receiveStream);
                    else
                        readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
                    result = readStream.ReadToEnd();
                    readStream.Close();
                }
                response.Close();
            }
            return result;
        }

        static void Main()
        {
            SeriesList<Series> serieslist = new SeriesList<Series>();

            // Загрузить html из сети интернет
            var pageContent = LoadPage(@"https://web.archive.org/web/20190926110623/https://animevost.org/");
            var document = new HtmlDocument();
            document.LoadHtml(pageContent);

            // Загрузить html локально
            //HtmlDocument document2 = new HtmlDocument();
            //document2.Load(@"H:\sample.txt");

            HtmlNodeCollection infoSeriesTitleURLPoster = document.DocumentNode.SelectNodes(".//td/div/a/img");
            HtmlNodeCollection infoSeriesView = document.DocumentNode.SelectNodes(".//div/div[2]/div[2]/span[1]");

            foreach (HtmlNode item in infoSeriesTitleURLPoster)
            {
                serieslist.Add(new Series(item.GetAttributeValue("title", "").Replace(""", ""),   // название
                                          item.GetAttributeValue("src", ""),                           // url постера
                                          item.GetAttributeValue("span", "")));                        // просмотры
            }
            int count = 0;
            foreach (HtmlNode item in infoSeriesView)
            {
                serieslist.Insert(item.InnerText, count++);
            }
            serieslist.ShowList();
            Console.ReadKey(true);
        }
    }
}

A: Давно не пробовал Html agility pack, но что-то типа такого:
var series = document.DocumentNode.SelectNodes(".//div[@class='shortstory']");

foreach (HtmlNode item in series)
{
    var title = item.SelectSingleNode(".//div[@class='shortstoryHead']/h2/a")?.InnerText;
    var posterUrl = item.SelectSingleNode(".//img[@class='imgRadius']")?.GetAttributeValue("src", "");
    var views = item.SelectSingleNode(".//span[@class='staticInfoRightSmotr']")?.InnerText;

    var element = new Series(title, posterUrl, views);
    serieslist.Add(element);
}

Выводит без сдвигов:
Название: Кандагава: Девушки на гидроциклах / Kandagawa Jet Girls [1 из 12+] [2 серия - 15 октября]
URL Постера: /web/20190926110623im_/https://animevost.org/uploads/posts/2019-09/1569439519_1.jpg
Просмотры: 15138

Название: Маг-обманщик из другого мира / Isekai Cheat Magician [1-12 из 12]
URL Постера: /web/20190926110623im_/https://animevost.org/uploads/posts/2019-07/1563784705_01-1.jpg
Просмотры: 3578543

Название: Рыцари усердия / Try Knights [1-9 из 12+]
URL Постера: /web/20190926110623im_/https://animevost.org/uploads/posts/2019-08/1565134513_1.jpg
Просмотры: 310173

Название: Рыцари усердия / Try Knights [1-9 из 12+]
URL Постера: poster_url
Просмотры: 310173

Как работает — смотрите объяснения в комментариях EvgeniyZ, он всё правильно вам сказал.


text:
Q: What tag export formats are there? I'm writing an importer for a CMS to import tags from various platforms/sources. I want to be able to import tags from WordPress, Moveable Type, Blogger; basically all of the big boys.
Are there any generic, standard tag export formats?

A: Based on your question, I'd assume you're looking for a common format that all of the big boys export to, which can then be consumed by your application. From what I can see, WordPress eXtended RSS appears to be pseudo-supported amongst WordPress, Movable Type, and Blogger. You might want to consider reading here for more information:
http://codex.wordpress.org/Importing_Content
This link does double duty for your question, since it also provides a comprehensive list of common blog engines, their export assumptions, and what formats you should consider supporting.
As for the WXR file format itself, it seems to be quite difficult to find a specification for in both Google and WordPress' own search database. Here's the most relevant result I could find:
http://olalindberg.com/blog/2008/12/13/write-your-own-wxr-file-to-migrate-custom-cms-to-wordpress
Good luck!


text:
Q: Required field not present on all pages leading to problems I have a 'Create' page in my MVC3 application that has 4 input fields that are all required. I also have an 'Edit' page in which 3 of these 4 fields can be edited. I do not want to display the 4th field and want to maintain it at its initial value (the field is the date that the entry was created ).
I mark the 4th field as [Required] in the model then this causes the model to be declared as invalid in post action method of the Edit field. If I omit the [Required] annotation then someone can create a user with a null value for this 4th field.
How can I get around this problem?

Model Code:
    [Required]
    [DisplayName("User Name")]
    public string UserName { get; set; }

    [Required]
    public string Role { get; set; }

    [Required]
    [DataType(DataType.Date)]
    [DisplayName("Insert Date")]
    public DateTime? InsertDate { get; set; }

    [Required]
    [DisplayName("Active")]
    public bool ActiveInd { get; set; }

Controller Code:
public ActionResult Edit(int id, ZUserRoleModel mod)
    {

        if (ModelState.IsValid)
        {

            // code removed

            return RedirectToAction("Index");
        }
        return View(mod);

    }

A: You can make that field as hidden in edit mode.
@Html.HiddenFor(x => x.EntryDate)

A: Not sure if you still need an answer for this, but what you need to do in order for the
@Html.HiddenFor(x => x.EntryDate )

to work, is pass an existing model into view. So let's assume that your action for getting the user data looks like this. ( You did not supply it, so I am not sure if this is right )
Public ActionResult GetUser(int UserID)
{
    ZUserRoleModel model = new ZUserRoleModel(UserID);
    // Maybe this could go to your database and gather user
    // It would populate the correct data into a model object

    return View("Edit", model);
}

With combination of the hidden field, your view will be populated with the existing user information, and the hidden field will be populated with data, and it will be passed to your edit action.
NOTE: I wrote this without any kind of testing, but it should still work, or at the very least, I hope it points you in the right direction if you still need assistance.

A: You can use fluentvalidation:  http://fluentvalidation.codeplex.com/
Have a rule that's something like
RuleFor(user => user.field4).NotEmpty().When(ViewContext.Controller.ValueProvider.GetValue("action").RawValue <> "edit")


text:
Q: How to document a Builder with its methods using JavaDoc I like to use the Builder pattern to instantiate objects of classes with complex states rather than using too many constructor arguments.
I can add a JavaDoc to the Class and each individual Method, but none of the JavaDoc keywords I know seems really fit to document the specificity of a builder, like what settings are mandatory, what are the defaults for optional settings.
If I document mandatory or optional and defaults for each individual method, it feels like the documentation is spread too much to get a global picture of it. Same if I document only the final build() method telling when it can build the instance with what defaults, and when it cannot.
None of these options seems really satisfying. It feels like JavaDoc does not fit so well with builder pattern but was designed for legacy Object Oriented code style; this or I don't understand it well enough.
I searched the https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html documentation but could not find an answer or guidance for documenting a Builder with proper tags.
@param looked like a valid candidate to document all the setFoo, withBar, addBaz from a builder at one place like the Builder class itself, but it seems not appropriate for this kind of usage.
How to properly document a Builder in JavaDoc or some other more appropriate tool?

A: Already your first assumption ("I can add a JavaDoc to the Class and each individual Method, […]") is wrong.
Documentation is still mandatory, and it should be done as closely to the source as possible. A JavaDoc comment is part of the source, so it cannot be closer!
People telling you that comments are an "anti-pattern" nowadays do not have a clue or are too lazy to type or both – and when you read the source for that "anti-pattern" crap, you will find that it talks about inline comments explaining what's happening in your code, but not about externalisable comments for documentation purposes – so not about JavaDoc or Doxygen comments (or how the respective tools are named in other languages).
To your question: a builder class will be documented like any other class as well, with the keywords provided by JavaDoc and proper descriptive text. If you are too lazy to add this text manually, you can write your own extension to JavaDoc and define your own keywords that will generate that text for you.
Or you create your own Annotation and refer to that in the main description. My sample below does both (annotation and descriptive text), to give you an idea what I am talking about (the definition for the annotation @IsMandatory is omitted).
But usually, a Builder will not have methods for mandatory attributes; instead these are the arguments for the Builder's constructor.
/**
 *
{@summary Builder for new instances of
 *  {@link MyObject}.}

 *
Attributes whose setter methods are marked with the
 *  {@link IsMandatory @IsMandatory}
 *  annotation are – obviously – mandatory. If not set before
 *  {@link #build()}
 *  is called, an
 *  {@link IllegalStateException}
 *  will be thrown.

 *
In particular, these are the attributes

 *

 *
{@link #setName(String) name}

 *    …
 *

 */
public final class MyObjectBuilder
{
  /**
   *  Creates a new instance of {@code MyObjectBuilder}.
   */
  public MyObjectBuilder() {…}

  /**
   *  Creates a new instance of
   *  {@link MyObject}.
   *
   *  @return The new instance.
   *  @throws IllegalStateException A mandatory attribute was not yet set.
   */
   public final MyObject build() throws IllegalStateException {…}

  /**
   *
{@summary Sets the name for the new instance of
   *  {@link MyObject}.} It can be any arbitrary string with more than
   *  one character that is not
   *  {@linkplain String#isBlank() blank}.

   *
Note: This attribute is mandatory! If missing,
   *  {@link #build()}
   *  will throw an
   *  {@link IllegalStateException}.

   *
   *  @param name The name for the new instance.
   *  @throws NullPointerException {@code name} is {@code null}.
   *  @throws IllegalArgumentException {@code name} is the empty string, or
   *      it is
   *      {@linkplain String#isBlank() blank}.
   */
  @IsMandatory
  public final void setName( final String name ) throws NullPointerException, IllegalArgumentException {…}

  /**
   *  Sets the other attribute for the new instance of
   *  {@link MyObject}.
   *
   *  @param other The other attribute.
   */
  public final void setOther( final Object other ) {…}
}

Have fun!


text:
Q: How to add a HTML document into a  via JavaScript/ JQuery? How do I add an HTML doc into a

 via JavaScript/ JQuery?
This is what i have so far;
emailBodyInclude.html
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="css/imports/reset.css" type="text/css" />

Hello world! This is HTML5 Boilerplate.

Using JavaScript/ JQuery, how can I go about removing from a HTML document any declarations of the form of:
<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">

So that I be left with:
<link rel="stylesheet" href="css/imports/reset.css" type="text/css" />

Hello world! This is HTML5 Boilerplate.

so that I can safely insert what remains into a

Thank you all in advance.
UPDATE:
emailBodyInclude.html is a String of HTML mail retrieved from a provider, like Yahoo, for example. It is dynamic, and there is no way to tell what the syntax will look like. I would like to include this html document inside another. Inside a

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="../../baseCSS/bootStrap/bootstrap.min.css">

This is a HTML email

A: You can use load for this    http://api.jquery.com/load/
$('.htmlMail').empty().load('emailBodyInclude.html');


text:
Q: How do I add the names of the graphs inside the plot in R? I built the graph but I try to add the names of the graphs and it does not work. It should look like in the picture, I only have the graphs without the names
I would happy if anyone knows which function should be used

A: The geomtextpath package looks as if it is ideal for this use case. Very nice it is too.
library(ggplot2)
library(geomtextpath)

ggplot(data.frame(x = 0)) +
  geom_textpath(stat = "function", fun = ~ 2.5 * .x,
                label = "Holding Cost",
                vjust = 1.1, colour = "green", hjust = 0.95, size = 6) +
  geom_textpath(stat = "function", fun = ~ 500 / .x ^0.5,
                label = "Set Up Cost",
                vjust = -0.1, colour = "blue", hjust = 0.95, size = 6) +
  geom_textpath(stat = "function", fun = ~ 500 / .x ^0.5 + 2.5 * .x,
                label = "Total Cost",
                vjust = -0.1, colour = "red", hjust = 0.95, size = 6) +
  xlim(1, 100)+
  theme_bw()

Created on 2022-03-24 by the reprex package (v2.0.1)


text:
Q: Converting mixed HTML text with PHP
Possible Duplicate:
How to parse and process HTML with PHP?

Can somebody help me to find a solution to parse text which has HTML and regular text. For example
This is my awesome text. Now starts a new line...

I push news to http://twitter.com .

This should become
This is my awesome text. Now starts a new line...

I push news to twitter.com .

I'm searching mainly for a magic regex replace function...At the moment I do
$text = preg_replace("@(src|href)=\"https?://@i",'\\1="', $description);
$text = nl2br(preg_replace("@(((f|ht)tp:\/\/)[^\"\'\>\s]+)@",'\\1', $text));

A: nl2br does the trick nicely.
file_get_contents('filename.html');
nl2br($text);

It was designed specifically for your needs.
If you're worried about double \ns or already present
 elements you have to devise a scheme either for the input text (if you have control over it) or for preprocessing.
Perhaps replacing all \n\n with \n and all
\n with \n before applying nl2br.

A: You can try this
$text = your source text
$text = preg_replace(
    array('/\n/m',  '/\
\
/m' '/\
$/'),
    array("\n
", "
", ''),
    $text
);

bye


text:
Q: How does extends work in classes? I've been trying to build a PDO extension, and I wanted to have special classes in different files but I wanted to have them all link to the same original class.
I have worked with some Frameworks and I see that they use the extends class keyword, and I thought that it added the class you are making to the class that you have given.
Some code I have tried is:
class PSMQuery extends PSM {

   // Functions and Jargon

}

I tried making an object for the original PSM class:
$psm = new PSM(/*Information*/);

But when I call the $psm variable like $psm->functionInTheExtendedClass it comes up with an error saying that it was an undefined method when I called it.
Am I using the extends keyword incorrectly?

A:
Am I using the extends keyword incorrectly?

You use it correctly, but it works the other way around.
If PSMQuery extends from PSM, this means you can access and use stuff from PSM in PSMQuery, but not the other way around.
I think to understand it you can use a good example:
class twoRoomApartment extends building { }

So now you can think logical and already see, that a two room apartment probably extends from a building and not the other way around.
Means now in your code, you just create an instance of PSMQuery.

A: It's inheritance.
Parent : PSM
Child   : PSMQuery
When you use extends you are extending parent class functionality and creating child class.
Your child class will inherit all the parent class functionality.
Parent will not get child class functionality.
So when u r trying to create object of parent class it doesn't know child class functionality.
You need to create object of child class and then you can access methods from parent class.


text:
Q: In the game of roulette there are 36 numbers that the ball may land on, other than the Zero. In the game of roulette, there are a few known (and playable) number pairs of 18 numbers each. The black/red, the even/odd, and the high/low numbers are known. But how many combinations of 18 different number sets are there? (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,and 18 would be the same as 18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2 and 1 because the opposite set would be composed of 19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35 and 36.). How would one go about to actually make the list, after the number of sets are known?

A: You'll need lots of paper; there are more than 4½ billion such partitions.
Once you've stocked up on pen and paper, decide that the first of the two sets will always be the one that contains 1. First write down all combinations where 2 is in the first set; then write down all combinations where 2 is in the second set; then you're done.
The first part of this can again be split into the ones where 3 is in the first set (with 1 and 2), and ones where 3 is in the second set. Continue by divide-and-conquer.
The base case of the recursion is when you have already decided on 18 numbers to go in one set or the other. Then there's only one way to place the remaining number, and the sublist you're writing has length 1.
The first few sets generated become
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 19
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 21
...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 36
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 18 19
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 18 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 18 21
...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 18 36
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 19 20
...
1 2 20 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
1 2 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
...

A: You have to choose 18 numbers out of a set of 36; the number of ways to do so is $\binom{36}{18}$, or 36 choose 18. This is equal to $\frac{36!}{18!18!}$, which is equal to 9075135300. If odd/even is considered the same as even/odd, we divide by 2 to get 4537567650.


text:
Q: (SQL) Select SUM of (Column 1) * Min(Column2) Where Column 1 and 2 share an ID I am quite new to SQL, so this query has been giving me a headache. For reference, I have two tables (Simplified versions):
CREATE TABLE PARTS_USED
(
    Part INT NOT NULL,
    Product INT NOT NULL,
    Quantity INT
    PRIMARY KEY(Part, Product)
);

and
CREATE TABLE SUPPLY
(
    Vendor INT NOT NULL,
    Part INT NOT NULL,
    Price DECIMAL(8,2) NOT NULL,
    PRIMARY KEY(Vendor, Part),
);

Product and Part are both unique IDs.
What I am trying to do here is get the Total "Cost" (sum of (Quantity * (Minimum Part Price))) of each product.
So far, I have this query:
CREATE VIEW PRODUCT_COST(ProductID, TotalCost)
AS
    SELECT
        PARTS_USED.Product,
        SUM(PARTS_USED.Quantity * (SUPPLY.Price))
    FROM
        PARTS_USED
    INNER JOIN
        SUPPLY ON PARTS_USED.Part = SUPPLY.Part
    GROUP BY
        PARTS_USED.Product;

However, I'm getting the MIN(SUPPLY.Price) is proving to be difficult; I want to be able to just change SUPPLY.Price in the SELECT line to MIN(SUPPLY.Price), but this does not work. With the way the tables are set up, I am quite lost as to how I should be using JOIN.

A: Because multiplication is commutative, you might be able to just take the product of the sum of quantity and the minimum price:
CREATE VIEW PRODUCT_COST(ProductID, TotalCost) AS
SELECT pu.Product, SUM(pu.Quantity) * MIN(s.Price) AS "Total Cost"
FROM PARTS_USED pu
INNER JOIN SUPPLY s ON s.Part = pu.Part
GROUP BY pu.Product;


text:
Q: Why the editor text doesn't change the text color in XamarinForms I set the property TextColor="White" but when I test the app the textColor of the editor is black
<ScrollView HeightRequest="90" Grid.Row="7" Grid.Column="0"
            IsVisible="{Binding TurnOnPrivacyPolicyMessage}">
   <Editor x:Name="txtMensaje" TextColor="White"
           BackgroundColor="Transparent" IsEnabled="False" >
   </Editor>
</ScrollView>

A: I use your code to test, but I find the Editor TextColor is white, not black.
Because you set Editor BackGroundColor is Transparent, the TextColor is white, you may not see Text clear, so I suggest you can set BackgroundColor as Gray or other to test.
<StackLayout>

        <Editor
            x:Name="txtMensaje"
            BackgroundColor="Transparent"
            TextColor="White" />

    </StackLayout>

The BackgroundColor is Transparent:

The BackGroundColor is Gray:

A: Use IsReadOnly instead - "The IsReadonly property does not alter the visual appearance of an Editor, unlike the IsEnabled property that also changes the visual appearance of the Editor to gray."  MS Docs


text:
Q: Why use base class pointers for derived classes class base{
    .....
    virtual void function1();
    virtual void function2();
};

class derived::public base{
    int function1();
    int function2();
};

int main()
{
    derived d;
    base *b = &d;
    int k = b->function1() // Why use this instead of the following line?
    int k = d.function1(); // With this, the need for virtual functions is gone, right?

}

I am not a CompSci engineer and I would like to know this. Why use virtual functions if we can avoid base class pointers?

A: The power of polymorphism isn't really apparent in your simple example, but if you extend it a bit it might become clearer.
class vehicle{
      .....
      virtual int getEmission();
 }

 class car : public vehicle{
      int getEmission();
 }

 class bus : public vehicle{
      int getEmission();
 }

 int main()
 {
      car a;
      car b;
      car c;
      bus d;
      bus e;

      vehicle *traffic[]={&a,&b,&c,&d,&e};

      int totalEmission=0;

      for(int i=0;i<5;i++)
      {
          totalEmission+=traffic[i]->getEmission();
      }

 }

This lets you iterate through a list of pointers and have different methods get called depending on the underlying type. Basically it lets you write code where you don't need to know what the child type is at compile time, but the code will perform the right function anyway.

A: You're correct, if you have an object you don't need to refer to it via a pointer. You also don't need a virtual destructor when the object will be destroyed as the type it was created.
The utility comes when you get a pointer to an object from another piece of code, and you don't really know what the most derived type is. You can have two or more derived types built on the same base, and have a function that returns a pointer to the base type. Virtual functions will allow you to use the pointer without worrying about which derived type you're using, until it's time to destroy the object. The virtual destructor will destroy the object without you knowing which derived class it corresponds to.
Here's the simplest example of using virtual functions:
base *b = new derived;
b->function1();
delete b;

A: its to implement polymorphism. Unless you have base class pointer
pointing to derived object you cannot have polymorphism here.

One of the key features of derived classes is that a pointer to a
  derived class is type-compatible with a pointer to its base class.
  Polymorphism is the art of taking advantage of this simple but
  powerful and versatile feature, that brings Object Oriented
  Methodologies to its full potential.
In C++, a special type/subtype relationship exists in which a base
  class pointer or a reference can address any of its derived class
  subtypes without programmer intervention. This ability to manipulate
  more than one type with a pointer or a reference to a base class is
  spoken of as polymorphism.
Subtype polymorphism allows us to write the kernel of our application
  independent of the individual types we wish to manipulate. Rather, we
  program the public interface of the base class of our abstraction
  through base class pointers and references. At run-time, the actual
  type being referenced is resolved and the appropriate instance of the
  public interface is invoked. The run-time resolution of the
  appropriate function to invoke is termed dynamic binding (by default,
  functions are resolved statically at compile-time). In C++, dynamic
  binding is supported through a mechanism referred to as class virtual
  functions. Subtype polymorphism through inheritance and dynamic
  binding provide the foundation for objectoriented programming
The primary benefit of an inheritance hierarchy is that we can program
  to the public interface of the abstract base class rather than to the
  individual types that form its inheritance hierarchy, in this way
  shielding our code from changes in that hierarchy. We define eval(),
  for example, as a public virtual function of the abstract Query base
  class. By writing code such as
  _rop->eval();
  user code is shielded from the variety and volatility of our query language. This not only allows for the addition, revision,
  or removal of types without requiring changes to user programs, but
  frees the provider of a new query type from having to recode behavior
  or actions common to all types in the hierarchy itself. This is
  supported by two special characteristics of inheritance: polymorphism
  and dynamic binding. When we speak of polymorphism within C++, we
  primarily mean the ability of a pointer or a reference of a base class
  to address any of its derived classes. For example, if we define a
  nonmember function eval() as follows, // pquery can address any of the
  classes derived from Query
   void eval( const Query *pquery ) { pquery->eval(); }
   we can invoke it legally, passing in the address of an object of any of the
  four query types:

    int main()
{
AndQuery aq;
 NotQuery notq;
OrQuery *oq = new OrQuery;
NameQuery nq( "Botticelli" ); // ok: each is derived from Query
// compiler converts to base class automatically
eval( &aq );
 eval( &notq );
eval( oq );
eval( &nq );
 }

whereas an attempt to  invoke eval() with the address of an object not derived from Query
     results in a compile-time error:
int main()
 { string name("Scooby-Doo" ); // error: string is not derived from Query
eval( &name);
}

Within eval(), the execution of pquery->eval(); must invoke the
  appropriate eval() virtual member function based on the actual class
  object pquery addresses. In the previous example, pquery in turn
  addresses an AndQuery object, a NotQuery object, an OrQuery object,
  and a NameQuery object. At each invocation point during the execution
  of our program, the actual class type addressed by pquery is
  determined, and the appropriate eval() instance is called. Dynamic
  binding is the mechanism through which this is accomplished.
   In the object-oriented paradigm, the programmer manipulates an unknown instance of a bound but infinite set of types. (The set of
  types is bound by its inheritance hierarchy. In theory, however, there
  is no limit to the depth and breadth of that hierarchy.) In C++ this
  is achieved through the manipulation of objects through base class
  pointers and references only. In the object-based paradigm, the
  programmer
  manipulates an instance of a fixed, singular type that is completely defined at the point of compilation. Although the
  polymorphic manipulation of an object requires that the object be
  accessed either through a pointer or a reference, the manipulation of
  a pointer or a reference in C++ does not in itself necessarily result
  in polymorphism. For example, consider

// no polymorphism
  int *pi;
// no language-supported polymorphism
  void *pvi;
// ok: pquery may address any Query derivation
  Query *pquery;

In C++, polymorphism
  exists only within individual class hierarchies. Pointers of type
  void* can be described as polymorphic, but they are without explicit
  language support — that is, they must be managed by the programmer
  through explicit casts and some form of discriminant that keeps track
  of the actual type being addressed.

A: You seem to have asked two questions (in the title and in the end):

*

*Why use base class pointers for derived classes?
This is the very use of polymorphism. It allows you to treat objects uniformly while allowing you to have specific implementation. If  this bothers you, then I assume you should ask: Why polymorphism?

*Why use virtual destructors if we can avoid base class pointers?
The problem here is you cannot always avoid base class pointers to exploit the strength of polymorphism.


text:
Q: Force plot() to use specific boundaries I want to use the 2d plot([x1,x2,x3,x1],[y1,y2,y3,y1]) to draw a triangle in my plot image. But how do I define the borders? the Diagram should not start on the motleft point and so forth but for example on the point of origin or any other point I like to use. Also it should end where I want. How to do that?
here the full code:
xs = [0,10,20,0];
ys = [30,50,30,30];
plot(xs,asinh(tan(ys*pi/180)));

the result I wanted:
xs = [0,10,20,0];
ys = [30,50,30,30];
plot(xs,(asinh(tan(ys*pi/180))*180/pi));
xlim([-10 30])
ylim([-10 60])

A: I'm not sure I understand your question. If you want to set the limits of the axes of your plot so that you can place your triangle anywhere within the plot:
Try xlim([xmin, xmax]) and ylim([ymin, ymax]) after you run the plot command: see http://www.mathworks.com/help/techdoc/ref/xlim.html
If you want to know how to draw a triangle by plotting points and connecting the points:
Try simply ordering x1, x2,x3 etc in the order in which you want to connect the dots and run plot so that it plots lines (which I believe it does by default). But to be explicit you can run plot([x1,x2,x3,x1],[y1,y2,y3,y1],'b-')  to make a blue line connecting the points.


text:
Q: Ошибка при загрузке web-приложения java на tomcat Изучаю spring, перевожу web приложение java на spring. При загрузке выскакивает ошибка:
One or more listeners failed to start.
Бьюсь с этим уже второй день, помогите пожалуйста хоть чем-нибудь(может направите на верный путь, вообще не знаю что делать уже)
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
 <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  version="4.0"
  metadata-complete="true">
 <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/root-context.xml</param-value>
 </context-param>
 <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    <load-on-startup>1</load-on-startup>
 </listener>
<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
    <display-name>Controller</display-name>
    <servlet-name>servlet</servlet-name>
    <servlet-class>web.MainServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>servlet</servlet-name>
    <url-pattern>/servlet</url-pattern>
</servlet-mapping>
<listener>
    <listener-class>web.MainSessionListener</listener-class>
</listener>
<error-page>
    <exception-type>java.lang.Throwable</exception-type>
    <location>/errorPage.jsp</location>
</error-page>
</web-app>

root-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
                           http://www.springframework.org/schema/data/jpa
                           http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context-4.3.xsd"
    default-autowire="byName">
    <bean id="MySqlDaoFactory" class="mysql.MySqlDaoFactory">
    </bean>
    <bean id="Connection" class="mysql.MySqlDaoFactory"
    factory-bean="MySqlDaoFactory" factory-method="getConnection">
    </bean>
    <bean id="studentDao" class="mysql.MySqlStudentDao"
    factory-bean="MySqlDaoFactory" factory-method="getStudentDAO">
    </bean>
    <bean id="subjectDao" class="mysql.MySqlSubjectDao"
    factory-bean="MySqlDaoFactory" factory-method="getSubjectDAO">
    </bean>
</beans>

A: У Вас отсутствует так называемый DispatcherServlet в web.xml.
    <servlet>
    <servlet-name>spring-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:path/to/your/mvc-context.xml
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>


text:
Q: GetPixel returns incorrect values This is my first post on this forum, please don't go hard on me if I didn't post it in the right place or if I did something wrong, I don't post in forums very much. So, I have this problem with GetPixel function. Basically, it should return the color decimal at x, y. The code I am about to post works perfectly on windows 7 32bit, but recently I bought a new laptop y50-70 with windows 8.1 64bit and the same code works completely different. I can't find any solution to the problem, can't even describe it. I think it could have something to do with desktop handle, HDC, GetDC(), GetPixel(), maybe even with my computer resolution, refresh rate or something like that... I have even recorded some videos which could help you understand the problem I am having because I can't even describe it correctly. It is like the real color is x = 219, y = 407 away from the place, where my mouse is pointing. The new laptop is 3 weeks old, I even tried to do system restore 1 time, but that didn't solve the problem.
Feel free to use this code, hope it will work fine for you:
#include <iostream>
#include <Windows.h>
using namespace std;

void Detect();

int main()
{
    Detect();

    return 0;
}

void Detect()
{
    POINT p;
    HDC hDC = GetDC(0);
    int x, y;

    while (!GetAsyncKeyState(VK_INSERT)) // Press insert to stop
    {
        GetCursorPos(&p);
        x = p.x;
        y = p.y;
        hDC = GetDC(0);
        cout << x << " " << y << " " << GetPixel(hDC, x, y) << endl;
        Sleep(50);
    }
    ReleaseDC(0, hDC);
}

Links to the problem below:
https://youtu.be/q2H2M8WLHVI
https://youtu.be/UcneHwXaGoM
If anyone could at least help somehow or tell what to do, where to go, I would very, very much appreaciate it. One of the main reasons why I started programming is because something like this, working with colours, conditions, etc... and now I can't advance further which is really sad. Hope to hear a reply. Thank you.

A: This is probably an issue with DPI scaling.
If your new monitor has a higher-than-average number of dots per inch, then Windows, by default, will stretch the graphics.  By default, Windows assumes that programs ignore the DPI.  If Windows didn't stretch the graphics, then programs that didn't adjust for the DPI would have tiny text in tiny windows on high-density displays.
This is a bit of a hack.  Some of the Windows APIs and messages that let you ask about the display and windows will translate the coordinates between an "average" 96 pixels-per-inch and whatever the actual DPI is for the monitor.  Likewise, the APIs that let you size things do the opposite transformation.  So this is all largely transparent to the program.  But it's not perfect because not all the APIs can do the scaling in a consistent manner.
So my guess is that your laptop has a high-resolution display, GetPixel doesn't translate coordinates for DPI scaling, and the mouse position is transformed for DPI scaling.  The result is that you're asking for a pixel that doesn't really line up with the mouse.
My suggested solution is the tell windows that your program is "DPI-aware".  There are several ways to do this.  The easiest in your case might be to call SetProcessDPIAware right at the beginning of your program.  You could also do this be marking your program in the manifest.  Depending on the compiler you're using, there might be a command line option to create the manifest you need automatically.

A: Another alternative that has worked for me, is to change a setting in the Control Panel, to disable per-device DPI Scaling. Are you running multiple monitors?
Win 8.1 introduced a new setting in the Control Panel, which says "Let me choose one DPI scaling for all displays". By defualt this is turned off. Turning it on has worked for me.
See this video to find the setting:
https://www.youtube.com/watch?v=sE3IUTPy1WA
I'm curious, so let me know if that works for you, when you don't use SetProccesDPIAware()


text:
Q: How to update certain tuples after deletion in a table I am trying to model a music streaming service data base in SQLite and I want to create this trigger: When a song is deleted from a playlist, every song that came after it needs to have its position decremented. I'm not really sure how to write this trigger.
Here is an example of the playlist's table (Sorry for the portuguese names. idMusica = Song ID; posicao = song's position in the playlist)

To further explain what I want here's an example:
If I delete song 6 from playlist 1, the position of song 11 would become 3.

A: I believe that the following will do as you wish :-
CREATE TRIGGER IF NOT EXISTS playlistreorder
    AFTER DELETE ON playlist
    BEGIN
        UPDATE playlist SET posicao = posicao -1 WHERE posicao > old.posicao AND idPlayList = old.idPlayList;
    END
;

*

*Note that the table names has been assumed to be playlist

Example
Consider the following test :-
DROP TABLE IF EXISTS playlist;
CREATE TABLE IF NOT EXISTS playlist (idMusica INTEGER, idPlayList INTEGER, posicao INTEGER);
INSERT INTO playlist (idMusica,idPlayList, posicao) VALUES
    (12,1,1),(5,1,2),(6,1,3),(11,1,4),
    (1,2,1),(2,2,2),(3,2,2),(4,2,4),(9,2,5)
;

CREATE TRIGGER IF NOT EXISTS playlistreorder
    AFTER DELETE ON playlist
    BEGIN
        UPDATE playlist SET posicao = posicao -1 WHERE posicao > old.posicao AND idPlayList = old.idPlayList;
    END
;
SELECT * FROM playlist;
DELETE FROM playlist WHERE posicao = 3 AND idplayList = 1;
SELECT * FROM playlist;

Example results
Before reorder (1st Query) :-

After reorder (2nd Query) :-

A: I'd argue that this approach is fundamentally wrong and overly fragile. Instead of tracking the absolute position in a playlist, track the relative position. That way you don't have to update positions when inserting or deleting songs:
If the first three songs have posicao values of 1,2,3, and you want to add a song at position 2, instead of updating the current 2 to 3, the current 3 to 4 and so on, use a new value halfway between the current 1 and 2 position's posicao's: 1.5 in this case.
When deleting, don't worry about filling in the gap; the posicao's on either side of the deleted song are still in the right order.
If you need the absolute position for some reason, you can calculate it in a SELECT on the fly with modern versions of sqlite (3.25 or newer) with something like
SELECT idMusica, row_number() OVER (ORDER BY posicao) AS pos
FROM playlist_songs
WHERE idPlaylist = :playlistid
ORDER BY posicao

or by just incrementing a counter in your program every time you fetch a row froma  given playlist as long as it's ordered by posicao.
Window function based queries for inserting into the middle of a playlist and deleting, given an absolute position (Though for deleting, if your junction table isn't a WITHOUT ROWID one, it's easier to track the rowid of the songs in your program and delete using the one for the selected song):
INSERT INTO playlist_songs(idMusica, idPlaylist, posicao)
VALUES(:songid, :playlistid
     , (SELECT (pos + prev_pos) / 2.0
        FROM (SELECT posicao AS pos
                   , lag(posicao, 1, 0.0) OVER (ORDER BY posicao) AS prev_pos
                   , row_number() OVER (ORDER BY posicao) AS rn
              FROM playlist_songs WHERE idPlaylist = :playlistid)
        WHERE rn = :position));

DELETE FROM playlist_songs
WHERE rowid = (SELECT rowid
               FROM (SELECT rowid, row_number() OVER (ORDER BY posicao) AS rn
                     FROM playlist_songs WHERE idPlaylist = :playlistid)
               WHERE rn = :position);


text:
Q: HERE API Pass Thru Waypoints Using the Routing REST API I need to be able to modify the default route.  To do that, I can add pass thru waypoints when calling calculateroute.  For example, if I am traveling from Edmonton, AB to Calgary, AB but I want to go via a different highway, I can geocode Stettler, AB and use the three waypoints in the call to the API.  However, I'm finding that the turn by turn instructions are going at the street level to the center of Stettler, AB, but I just want to stay on the highway and pass through Stettler.  How can I specify pass thru waypoints (through/near a town) that are not routing specifically to the exact coordinate?

A: The Routing API uses the specified waypoints and your travel mode (car, truck, fastest, shortest, traffic, etc) to find the best routes. To go through locations that you desire, your waypoints should be at/close to those locations. Also, you can specify if you want alternate routes to be calculated, then you can choose the route that you desire. You can also use the avoidAreas parameter to avoid certain areas you do not want the route to pass through.


text:
Q: A fast converging limit for $\ln x$ (or why $\ln 2 \approx \sqrt{\sqrt{42}-6})$ I've read a lot about approximating logarithms recently, and apparently it's not easy. It can be done by Taylor series (slow convergence), by continued fractions (also slow) and also by some limits.
I had an idea to increase the accuracy of a limit approximation by using the Taylor series for $\cosh t$. The limit I got is:
$$\ln x=\lim_{N \to \infty} N \sqrt{2 \left(\sqrt{3} \sqrt{x^{1/N}+x^{-1/N}+1} -3\right)}$$
This limit looks awkward, for sure, but it gives very good approximations for $x$ close to $1$.
For example, even if we take the smallest possible value for $N$, we obtain the value for $\ln 2$ accurate for three digits:
$$N=1,~~~~~x=2$$
$$\sqrt{\sqrt{42}-6}-\ln 2 \approx 0.00021$$
Using the properties of logarithms, we can approximate larger arguments as well, like $\ln 3$:
$$N=1,~~~~~x=\frac{3}{2}$$
$$\sqrt{\sqrt{42}-6}+\sqrt{\sqrt{38}-6}-\ln 3 \approx 0.00022$$

The outline of a proof:
$$\cosh \frac{t}{N}=1+\frac{t^2}{2N^2}+\frac{t^4}{24N^4}+\cdots$$
Now we take only the first three terms and solve the quadratic equation for $t^2=\ln^2 x$.

How does this limit compare to other ways of computing logarithms? I understand that using radicals is not as convenient as rational approximations, but maybe it has some advantages?


text:
Q: Coded Ui WaitForControlReady(200) does not break on timeout Description: MFC Application
Desired action - check if a sub window open. Identify the sub window by a unique button located in the window.
Issue: When window is closed, The following code instead of returning false after 200 ms waits 7 seconds = timeout does not work.
The GeneralUIMap winwindow represents the button, since the button itself does not have unique search properties, and can only be uniquely identified by the WinWindow wrapper GeneralUIMap:
class x{
     private UITestControl mainApplicationWindow; //main application window
     private WinWindow GeneralUIMap;
     private WinButton btnZoomAdd;

     X(){
        mainApplicationWindow = new WinWindow();
        mainApplicationWindow.TechnologyName = "MSAA";
        mainApplicationWindow.SearchProperties UITestControl.PropertyNames.Name] = " - Main Window - Welcome";

        GeneralUIMap = new WinWindow(mainApplicationWindow);
        GeneralUIMap.SearchProperties[WinWindow.PropertyNames.ControlId] = "8546";
        btnZoomAdd = new WinButton(GeneralUIMap);

    }
    public bool isVisible()
    {
        WinWindow w = new WinWindow(mainApplicationWindow);
        w.SearchProperties[WinWindow.PropertyNames.ControlId] = "8546";

        try
        {
            w.WaitForControlReady(200);
        }
        catch (Exception e)
        {
            return false;
        }

        return true;
    }

A: Does the window exist when you wait for it to be ready? If not, the function will raise a null exception. This exception takes time to come since Coded UI tries to find the control before to give up and returns null.
Use WaitForControlExist() or TryFind() as condition before to use WaitForControlReady().
Also WaitForControlReady() will return false if the timeout is reached. But your code actually will always returns true (if there is no exception) since you do not evaluate the value of WaitForControlReady().
Instead of try catch, use this:
if (w.TryFind() && w.WaitForControlReady(200))
{
    return true;
else
{
    return false;
}

IMO, 200 ms is really a short amount of time for a timeout. It could lead to false errors. In other cases that UI performance validation, you should have reasonable timeouts. The default timeout is 3000 ms in Coded UI, which should be sufficient. But don't hesitate to increase it.
Remember than a timeout will be reached only when the condition is not meet unlike delay where the action will wait until the end regardless the status of the object. Plus, automated tests will still be faster than human over all because of its regularity.
A last remark, your method "IsVisible()" does not exactly return the visible status of the window. With Coded UI, I think you can considere that a control is visible when you have a clickable Point or check the ControlStates:
w.WaitForControlPropertyNotEqual(UITestControl.PropertyNames.State, ControlStates.Invisible)

and maybe too:
w.WaitForControlPropertyNotEqual(UITestControl.PropertyNames.State, ControlStates.Offscreen);


text:
Q: PDF encryption on Google App Engine We're using Google App Engine (java flavour) and we want to encrypt our PDF's with the default PDF encryption using one (or two) passwords.
That's something a lot a libraries do quite fine, such as iText and Apache's PDFBox.
But, in Google App Engine there are restrictions on what (java) libraries can be used. In our case, GAE doesn't allow the use of BouncyCastle encryption libraries.
We tried several PDF libraries (pdfbox, itext, pdfjet and more) but all need at least those libraries and fail to encrypt our in-memory byte[] of a PDF.
On GAE's blog, Google has accepted the request to support BouncyCastle, but there's no information when it might me available... Does anybody know more about that? I already put a question on the forum overthere, no reply yet.
There's a approach, but I need help or advise for that:

*

*SunJCE (and many others) security providers ARE allowed, so how much work would it be or is it a good idea to make a change in iText's sources (is opensource) and let it work with another provider? Is that something you would advice us to do? Or, is that weeks-and-weeks of work and custom algorithm-coding?
What would be the steps? I don't know enough about Java encryption libraries to checkout if this is a valid route to follow.

Allowed providers according to a google forum:

*

*INFO: Found security provider SUN version 1.6

*INFO: Found security provider SunRsaSign version 1.5

*INFO: Found security provider SunJSSE version 1.6

*INFO: Found security provider SunJCE version 1.6

*INFO: Found security provider SunJGSS version 1.0

*INFO: Found security provider SunSASL version 1.5

*INFO: Found security provider XMLDSig version 1.0

*INFO: Found security provider SunPCSC version 1.6

*INFO: Found security provider SunMSCAPI version 1.6

Any advice?


text:
Q: Claw and co-claw free graphs Suppose I want to define the class of claw and co-claw free graphs? The graphs G such that neither G nor its complement contains an induced claw ($K_{1,3}$).
Do these graphs have any kind of interesting structure besides what is already implicit? What would good examples be? So far I can think of cycles, $K_n$ minus an edge, cocktail party graphs (http://mathworld.wolfram.com/CocktailPartyGraph.html). Also the house graph ($C_5$ plus an edge), and a few other small graphs. (And their complements of course).

A: An easy to understand subclass of these are the $\{K_3,K_{1,3}\}$-free graphs. (These are a subclass because $K_3$ is a subgraph of $\overline{K_{1,3}}$.)
Such graphs can have maximum degree $2$, because if a vertex $v$ has neighbors $w_1,w_2,w_3$, then either they are independent (and form a $K_{1,3}$ together with $v$) or there is an edge $w_i w_j$ (which forms a triangle together with $v$). So we can classify these completely: they are the disjoint unions of islated vertices, paths, and cycles of length at least $4$.
Similarly, the complements of these graphs form a nice subclass, the $\{\overline{K_3},\overline{K_{1,3}}\}$-free graphs, which we now also understand.
I will now show that these are the only cases when the number of vertices is sufficiently large (at least $11$).
In a general $\{K_{1,3},\overline{K_{1,3}}\}$-free graph, the neighborhood $N(v)$ of any vertex $v$ is $\{\overline{K_3},\overline{K_{1,3}}\}$-free, and the co-neighborhood $\overline{N}(v)$ is $\{K_3,K_{1,3}\}$-free. But these cannot both be large. Whenever $w \in N(v)$ has neighbors $x_1,\dots,x_k$ in $\overline{N}(v)$, then $x_1, \dots, x_k$ must form a clique: if $x_ix_j$ is not an edge, then $\{w,x_i,x_j,v\}$ induce a $K_{1,3}$. But $\overline{N}(v)$ is $K_3$-free, so $k \le 2$. and there are at most $2|N(v)|$ edges between $N(v)$ and $\overline{N}(v)$.
Similarly, there are at most $2|\overline{N}(v)|$ non-edges. But there are $|N(v)| \cdot |\overline{N}(v)|$ pairs of vertices here which are either edges or non-edges. So
$$|N(v)| \cdot |\overline{N}(v)| \le 2|N(v)| + 2|\overline{N}(v)| \iff (|N(v)|-2)(|\overline{N}(v)|-2) \le 4.$$
Suppose the graph is large (it has $n>10$ vertices). Then the only way to satisfy this inequality is to make sure that every vertex has either degree or co-degree $2$. But if there's a vertex $v$ with degree at most $2$, and a vertex $w$ with co-degree at most $2$, then there are $n-5$ vertices adjacent to $w$ but not $v$, and among these vertices there cannot be either a $K_3$ or an $\overline{K_3}$. This is impossible by Ramsey's theorem.
Thus, aside from small examples, these graphs either have maximum degree $2$ or maximum co-degree $2$, and we've already figured out what both of these cases are like.
The largest example I've found not of this type is the Paley graph on $9$ vertices,

which you can find on House of Graphs here. (Like all Paley graphs, it's self-complementary, so it's enough to check that it's claw-free, which it is.) I don't have a proof that there is no $10$-vertex example.

A: The {claw,co-claw}-free graphs were characterized (in fact, classified) by Pouzet, Kaddour, and Trotignon in the following paper:
M. Pouzet, H. Si Kaddour, N. Trotignon, Claw-freeness, 3-homogeneous subsets of a graph and a reconstruction problem. Contrib. Discrete Math. 6 (2011), no. 1, 86–97.
Theorem 1.1 in the paper states that the class of {claw, co-claw}-free graphs consists of the graph obtained from the triangle ($K_3$) by gluing a triangle along each edge; of the induced subgraphs of $L(K_{3,3})$ (the line graph of the complete bipartite graph $K_{3,3}$); of graphs whose connected components are cycles of length at least 4 or paths; and of the complements of these graphs.
link to the web page of the paper


text:
Q: How to get browser console error messages using Selenium WebDriver + Java? After tests are run, I want to collect all console error messages displayed in the console(Open Firebug -> Click on Console -> Click on Errors) using Selenium WebDriver + Java.
I tried the answer mentioned here, but it only displays messages for 'Warnings', 'Info' but not for 'Errors'
I want only Console errors like -

Can someone please help me how to get those Console log?

A: Use JSErrorCollector, to collect javascript errors (those coming up in the console) from firefox through java.
it gets as simple as this,
final List<JavaScriptError> jsErrors = JavaScriptError.readErrors(driver);


text:
Q: Access file system through query string or params I have been given a task of reproducing the issue/testing the unauthorized access to file system through request.param and query string.
For instance i have something like this. request.querystring("blah");
How could somebody pass "../../../b1/b2" in the query string and access file system.
This may be related to cross site scripting.
Need help..at least provide resources. Thanks in advance.

A: Wish I could provide a definitive answer, but can at least steer you in some direction.  Not sure how confident you are that request.querystring() was indeed responsible, but some possibilities are:
Directory Traversal/Path Traversal:
Overview: http://en.wikipedia.org/wiki/Directory_traversal
Testing For: http://www.owasp.org/index.php/Testing_for_Path_Traversal
Remote File Inclusion:
Overview: http://en.wikipedia.org/wiki/Remote_file_inclusion
Tutorial: http://www.offensivecomputing.net/?q=node/624 (KnightLighter's Tutorial)
Hope this moves you in the right direction.


text:
Q: HDMI video card on older PC, how to tell if audio supported? I've been asked by a friend who isn't that computer-skilled, to suggest a cheap 2nd hand PCIe video card so he can connect his  PC to his new HDMI TV. The PC is S775-era G35 Intel/Dell running Microsoft MSDN DVD based Windows 8.1 (i.e. not a Dell customisation of Windows).
Finding a cheap AMD/nVidia PCIe video card with HDMI out, on EBay, is dead easy. But I remember issues many years ago with HDMI and audio. I can't remember if they were specific to older Windows, older Intel chipsets, older video card chips, or whatever.
(FWIW I'm on newer hardware myself and on Windows I tweak the disabled sound devices to copy any audio to HDMI as well as the usual speakers, so its a while since I did much with S775 gen boards, or had to worry about HDMI audio working automatically, and I'm remote from him so I won't be able to fix it on the spot if it arrives and there's an issue making it work).
How can I check/be sure whether a card I pick for him will handle HDMI audio properly?


text:
Q: MP3 Feature Extraction I want to read mp3 file and extract its features which I will use further for identifying mood of song. Can u help me in extracting feature of mp3 and which feature will b most appropriate for mood identification?

A: You could start by working out the BPM. I found this random BPM detector in java, which you might be able to use.
if (bpm > 180) {
    // frantic
} else if (bpm > 140) {
    // bouncy psytrance
} else {
    // "down beat"
}

Or maybe you could use this opensource project for music identification called Echoprint, then programmatically search for song on google and tag cloud the results.

A: java_mp3 is simple API which provides the MP3File wrapper over native java.io.File. Then you can call the getters to access its metadata. Though it is not supported anymore as far as the last bundle date says, but it works, ID3v2 does not change over time, so its ok.
Description says:

A Java library to read and modify ID3 and ID3v2 tags on MP3 files and
  gather extended information about MP3 files.

There is similar answer on StackOverFlow, which suggests using JAudioTagger which supports reading MP3 ID3v1,ID3v11, ID3v2.2, v2.3 and v2.4 metadata.
Then you can write your own algorithm defining mood of songs based on gathered metadata analysis.


text:
Q: How do i run a "git rev-parse" on Heroku? I'm writing an API that's using django-rest-framework (but the framework, nor the language matter at this point).  I've got a diagnostic API endpoint "/version" that reads some data from a file (the last git checkin ID) and then spits it back out.  the code looks like this:
class Version(APIView):
    permission_classes = (IsAdminUser,)

    def get(self, request):
        git_version_file = open('gitversion', 'r')
        checkin_id = git_version_file.read().strip()
        return Response({'version' : checkin_id})

Normally (on my dev machine) this is easy as I can call a git post-commit hook to create the file (the command would be git rev-parse --short HEAD > gitversion. Obviously, this file cannot be checked into git.
However, I want this to work on my instances that are deployed on heroku.  Of course, I can use the "heroku releases" command, however I want this to be available programmatically (by people who don't have access to the "heroku" command line command).
I can't run this on a one-off dyno as the filesystems are not the same.  I'm not sure how I can accomplish this at this point.


text:
Q: Golang for loop package main

import "fmt"

func main() {
   num := []int{}
   fmt.Println(num)
   for i := 1; i <= 64; i++ {
      if i == 1 {
        num = append(num, i)
      } else if i == 2 {
        num = append(num, i)
      } else if i == 3 {
        num = append(num, 4)
      } else {
        num = append(num, 2*(num[len(num)-1]))
            // get last item
    }
}
for _, s := range num {
    fmt.Println(s)
}
}

I'm beginner level on golang and tried to make a for loop as above. Actually I just wanted to solve that famous chess board and wheat question. You can see the url below. But on the last item it gives a negative result if i=64. I just couldn't figure it out why it is negative. Can you help me please, thank you in advance.
https://en.m.wikipedia.org/wiki/Wheat_and_chessboard_problem
Edit:
Here's the solution
package main

import "fmt"

func main() {
num := []uint64{}
var total uint64 = 0

fmt.Println(num)
for i := 1; i <= 64; i++ {
    if i == 1 {
        num = append(num, uint64(i))
    } else {
        num = append(num, 2*(num[len(num)-1]))
        // get last item
    }
}
for _, s := range num {
    fmt.Println(s)
}
for _, s := range num {
    total += s
}
fmt.Println("Total: ", total)
}

A: because the last number 9223372036854775808 is out bound of int64, https://pkg.go.dev/builtin#int64
change to uint64 works.
package main

import "fmt"

func main() {
    num := []uint64{}
    fmt.Println(num)
    for i := 1; i <= 64; i++ {
        if i == 1 {
            num = append(num, uint64(i))
        } else if i == 2 {
            num = append(num, uint64(i))
        } else if i == 3 {
            num = append(num, uint64(4))
        } else {
            num = append(num, 2*(num[len(num)-1]))
            // get last item
        }
    }
    for _, s := range num {
        fmt.Println(s)
    }
}

gives
[]
1
2
4
8
16
32
64
128
256
512
1024
2048
4096
8192
16384
32768
65536
131072
262144
524288
1048576
2097152
4194304
8388608
16777216
33554432
67108864
134217728
268435456
536870912
1073741824
2147483648
4294967296
8589934592
17179869184
34359738368
68719476736
137438953472
274877906944
549755813888
1099511627776
2199023255552
4398046511104
8796093022208
17592186044416
35184372088832
70368744177664
140737488355328
281474976710656
562949953421312
1125899906842624
2251799813685248
4503599627370496
9007199254740992
18014398509481984
36028797018963968
72057594037927936
144115188075855872
288230376151711744
576460752303423488
1152921504606846976
2305843009213693952
4611686018427387904
9223372036854775808


text:
Q: Enscript: How to use a different font? I downloaded the font RobotoMono-Regular.ttf here, converted it to RobotoMono-Regular.afm with this tool and copied this file to /usr/local/share/enscript/afm where other .afm  files reside. In there is also the file font.map. I added the entry RobotoMono-Regular RobotoMono-Regular (the first entry is the font name, the second the file base name of the .afm. When I use enscript --font=RobotoMono-Regular ..., I don't get the new font, though. Is there anything else that needs to be done? File permissions seem all fine. If I specify the font names of other fonts saved as .afm in this directory, enscript respects them.
This is under macOS. The question here seems somewhat related but is different.

A: The .afm files are font metrics, that say how much space to leave for each character, so enscipt can calculate where to put line breaks and so on.  To actually draw the characters a printer also needs the PostScript code describing how to draw each character. This is in a separate .pfa (or .pfb) file that you must also provide in the afm directory, with the same basename as the .afm file.
Check if the pfa files was also generated by your web-tool. If not, you can use ttf2pt1 which should be in some suitable package for your system.
When enscript sees the 2 files, it "downloads" the pfa file so it is included into the output and the printer then knows how to print everything.  The other fonts you see there without a pfa file are standard fonts that the printer is expected to have built-in, so no download is needed. Using enscript -v should show you a message like
downloading font "RobotoMono-Regular"

By printer, I include programs like GhostView (gv) and so on.