text:
Q: How do I echo text in capital letters? I want to know how to capitalize in PHP

A: The strtoupper() function is what you're looking for.

A: echo strtoupper('hello');

strtoupper will capitalize the whole string.
If you're only interested in capitalizing the first letter, you can use ucfirst:
echo ucfirst('hello!'); //Hello!

If you want to capitalize the first letter of each word in a string, use ucwords:
echo ucwords('hello world!'); //Hello World!


text:
Q: Upgrade R version from 3.2.2 to 3.3.3 I currently have R-3.2.2 version installed on my linux server. Is there a way to use yum install command to upgrade the R version to R-3.3.3 version only.
When i do yum install R i see that the latest version which is 3.4.1 is installed. But i want to install only R-3.3.3 version.
yum --showduplicates list r | expand
*Note* Red Hat Network repositories are not listed below. You must run this command as root to access RHN repositories.
Loaded plugins: aliases, presto, product-id, refresh-packagekit, rhnplugin,
              : security, tmprepo, verify, versionlock
Installed Packages
R.x86_64                     3.3.3-1.el6                     @epel
Available Packages
R.x86_64                     3.2.3-4.el6                     HDP-UTILS-1.1.0.21
R.x86_64                     3.2.3-4.el6                     HDP-UTILS-2.5.0.0
R.x86_64                     3.2.3-4.el6                     HDP-UTILS-2.6.0.3
R.x86_64                     3.2.3-4.el6                     HDP-UTILS-2.6.0.3-8
R.x86_64                     3.4.1-1.el6                     epel

--------------------------------------------
sudo yum install R-3.3.3-1
Loaded plugins: aliases, presto, product-id, refresh-packagekit, rhnplugin, security, tmprepo, verify, versionlock
This system is receiving updates from RHN Classic or RHN Satellite.
Setting up Install Process
No package R-3.3.3-1 available.
Error: Nothing to do

sudo yum install r-3.3.3-1.el6
Loaded plugins: aliases, presto, product-id, refresh-packagekit, rhnplugin, security, tmprepo, verify, versionlock
This system is receiving updates from RHN Classic or RHN Satellite.
Setting up Install Process
No package r-3.3.3-1.el6 available.
  * Maybe you meant: R
Error: Nothing to do
sudo yum install R-3.3.3-1.el6
Loaded plugins: aliases, presto, product-id, refresh-packagekit, rhnplugin, security, tmprepo, verify, versionlock
This system is receiving updates from RHN Classic or RHN Satellite.
Setting up Install Process
Nothing to do

A: update
Your package list says R.x86_64 3.3.3-1.el6 is installed version. Are you sure it's not?
You can check version with R --version from command line or R.version.string from within R. If it's not 3.3.3, I'd suggest trying sudo yum remove r and re-installing desired version sudo yum install r-3.3.3-1.el6
end of uptate
You should first find out exact version name and then install it as described here. Something like this:
$ yum --showduplicates list r | expand

will give you exact naming of versions available from your repo and they install it as (replace 3.3.3 with the version you find in the list)
$ sudo yum install r-3.3.3

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular 2 routerLink optional parameters I have the like following in my markup:

    <p [routerLink]="['profiles', profiles[i], 'posts', posts[i], 'likes', likes[i]]"

In my Angular Component I have the following arrays:
profiles: any = []
posts: any = []
likes: any = []

Sometimes my "profiles" array might have elements and not my other arrays.  If this happens then the routing will be broken.  I have tried adding "?" to mark is as optional:
<p [routerLink]="['profiles', profiles[i]?, 'posts', posts[i]?, 'likes', likes[i]?]"

This doesn't exactly work.

A: Angular supports three different kinds of routing parameters:

*

*Required

*Optional

*Query

The syntax for each type is slightly different and you have to use the correct syntax for each of the types to work correctly.
See this post for more information: Sending data with route.navigate in Angular 2


text:
Q: Access deeper elements of a JSON using postgresql 9.4 I want to be able to access deeper elements stored in a json in the field json, stored in a postgresql database.  For example, I would like to be able to access the elements that traverse the path states->events->time from the json provided below.  Here is the postgreSQL query I'm using:
SELECT
    data#>> '{userId}' as user,
    data#>> '{region}' as region,
    data#>>'{priorTimeSpentInApp}' as priotTimeSpentInApp,
    data#>>'{userAttributes, "Total Friends"}' as totalFriends
from game_json
WHERE game_name LIKE 'myNewGame'
LIMIT 1000

and here is an example record from the json field
{
    "region": "oh",
    "deviceModel": "inHouseDevice",
    "states": [
        {
            "events": [
                {
                    "time": 1430247045.176,
                    "name": "Session Start",
                    "value": 0,
                    "parameters": {
                        "Balance": "40"
                    },
                    "info": ""
                },
                {
                    "time": 1430247293.501,
                    "name": "Mission1",
                    "value": 1,
                    "parameters": {
                        "Result": "Win ",
                        "Replay": "no",
                        "Attempt Number": "1"
                    },
                    "info": ""
                }
            ]
        }
    ],
    "priorTimeSpentInApp": 28989.41467999999,
    "country": "CA",
    "city": "vancouver",
    "isDeveloper": true,
    "time": 1430247044.414,
    "duration": 411.53,
    "timezone": "America/Cleveland",
    "priorSessions": 47,
    "experiments": [],
    "systemVersion": "3.8.1",
    "appVersion": "14312",
    "userId": "ef617d7ad4c6982e2cb7f6902801eb8a",
    "isSession": true,
    "firstRun": 1429572011.15,
    "priorEvents": 69,
    "userAttributes": {
        "Total Friends": "0",
        "Device Type": "Tablet",
        "Social Connection": "None",
        "Item Slots Owned": "12",
        "Total Levels Played": "0",
        "Retention Cohort": "Day 0",
        "Player Progression": "0",
        "Characters Owned": "1"
    },
    "deviceId": "ef617d7ad4c6982e2cb7f6902801eb8a"
}

That SQL query works, except that it doesn't give me any return values for totalFriends (e.g. data#>>'{userAttributes, "Total Friends"}' as totalFriends).  I assume that part of the problem is that events falls within a square bracket (I don't know what that indicates in the json format) as opposed to a curly brace, but I'm also unable to extract values from the userAttributes key.
I would appreciate it if anyone could help me.
I'm sorry if this question has been asked elsewhere.  I'm so new to postgresql and even json that I'm having trouble coming up with the proper terminology to find the answers to this (and related) questions.

A: You should definitely familiarize yourself with the basics of json
and json functions and operators in Postgres.
In the second source pay attention to the operators -> and ->>.
General rule: use -> to get a json object, ->> to get a json value as text.
Using these operators you can rewrite your query in the way which returns correct value of 'Total Friends':
select
    data->>'userId' as user,
    data->>'region' as region,
    data->>'priorTimeSpentInApp' as priotTimeSpentInApp,
    data->'userAttributes'->>'Total Friends' as totalFriends
from game_json
where game_name like 'myNewGame';

Json objects in square brackets are elements of a json array.
Json arrays may have many elements.
The elements are accessed by an index.
Json arrays are indexed from 0 (the first element of an array has an index 0).
Example:
select
    data->'states'->0->'events'->1->>'name'
from game_json
where game_name like 'myNewGame';
-- returns "Mission1"

A: select
    data->'states'->0->'events'->1->>'name'
from game_json
where game_name like 'myNewGame';

This did help me


text:
Q: When does sum of two units give a unit? Let $A$ be a ring and $u,v \in A^\times$. When do we have that $u + v \in A^\times$?
I think that A is needed to be an integral domain. For example consider $\mathbb{Z/6}$. Both $1$ and $5$ is a unit but their sum $1+5=0$ is not a unit.

A: I do not think there is such a condition. For any unital ring such that $1 \neq 0,$ $1$ and $-1$ are units, but $1+(-1)=0,$ which is not a unit.

A: I don't sure about an answer for your question. However, there is a nice result of F. Beukers and Schlickewei about the number of solutions of the unit equation in a finitely generated subgroup.

A: In any field, the sum of two units is a unit, unless they're additive inverses.  For a non-field example, let $\zeta$ be a primitive sixth-root of unity and let $A$ be the ring of integers in $\mathbb{Q}[\zeta]$. Then note that $\zeta^2+1 = \zeta$.  (Because $0 = \zeta^6 - 1 = (\zeta^3-1)(\zeta^3+1) = (\zeta-1)(\zeta^2+\zeta+1)(\zeta+1)(\zeta^2-\zeta+1)$ and we can set this last factor equal to $0$.)


text:
Q: Fastest way of opening new page What is fastest way in following case(Using spring-webmvc 4.1.2)?

*

*There are 3 Controllers and 3 Services.

*A-Controller call A-Service and show Page-A.

*B-Controller call B-Service and show Page-B.

*C-Controller call C-Service and show Page-C.

*If user click Page-A's submit button, open Page-B.

*We have to run A-Service before open Page-B.

*If user click Page-C's submit button, open Page-B.

*We have to run C-Service before open Page-B.

I don't want to run ServletFilter twice, so I want to avoid forward.
And I don't want to use redirect because of that is too slow.
I have 2 ideas.

*

*Call B-Controller and autowire A-Service and C-Service in the B-Service.
We resolve which service to use according to RequestParameter.
But I don't know how to autowire in this case.

*Call B-Controller in the A-Controller.
But this way is too bad. Because We have to inject component in our own.
Please tell me witch one is good, or Please tell me another best way.


text:
Q: Adding Python package to Sql Server 2017 machine learning services breaks it I am trying to get started running python inside of Sql Server 2017 with Python Machine Learning Services.
Out of the box it works and I can run simple scripts like listing the installed packages:
EXEC sp_execute_external_script
@language = N'Python',
@script = N'import pkg_resources
print([p.project_name for p in pkg_resources.working_set])'

When I want to add a new package I follow the Microsoft documentation for 2017: https://learn.microsoft.com/en-us/sql/machine-learning/package-management/install-python-packages-standard-tools?view=sql-server-2017
which says to basically just pip install the new package. So I go to the sql server python install:
C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\PYTHON_SERVICES

and run:
scripts\pip.exe install pyarrow

This installs an upgraded numpy version as a dependency and when I then try to call even simple python scripts like above I get the following error:
Msg 39012, Level 16, State 1, Line 0
Unable to communicate with the runtime for 'Python' script. Please check the requirements of 'Python' runtime.

Nothing will run while numpy is in this newer version. I can fix the issue by repairing the Sql Server install from the installation media, but that gets me back to my initial setup without the required pyarrow package.
After trying to troubleshoot (incl. installing specific versions of pandas and numpy) I now can't get back to a working state with repairs - will try uninstall and reinstalling the feature.
I can see that the procedure has changed for installing python packages in Sql Server 2019 (https://learn.microsoft.com/en-us/sql/machine-learning/package-management/install-additional-python-packages-on-sql-server?view=sql-server-ver15) so there might be some flaws in 2017 but I can't find it documented anywhere.
I run the latest Sql Server 2017 (cu21) developer edition.
Some suspects:

*

*I'm not too familiar but it says in multiple places that Sql Server 2017 Machine Learning services comes with Conda and I'm not sure if Conda and pip are compatible?

*The error suggests a dependency from microsofts revoscalepy on pandas and again from pandas on numpy.

Current full error:
Msg 39012, Level 16, State 1, Line 0
Unable to communicate with the runtime for 'Python' script. Please check the requirements of 'Python' runtime.
STDERR message(s) from external script:
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\PYTHON_SERVICES\lib\site-packages\revoscalepy\__init__.py", line 99, in <module>
    from .RxSerializable import RxMissingValues
  File "C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\PYTHON_SERVICES\lib\site-packages\revoscalepy\RxSerializable.py", line 10, in <module>
    from pandas import DataFrame
  File "C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\PYTHON_SERVICES\lib\site-packages\pandas\__init__.py", line 39, in <module>
    from pandas.core.api import *
  File "C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\PYTHON_SERVICES\lib\site-packages\pandas\core\api.py", line 10, in <module>
    from pandas.core.groupby import Grouper

STDERR message(s) from external script:
  File "C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\PYTHON_SERVICES\lib\site-packages\pandas\core\groupby\__init__.py", line 1, in <module>
    from pandas.core.groupby.groupby import GroupBy  # noqa: F401
  File "C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\PYTHON_SERVICES\lib\site-packages\pandas\core\groupby\groupby.py", line 25, in <module>
    from pandas.util._validators import validate_kwargs
  File "C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\PYTHON_SERVICES\lib\site-packages\pandas\util\_validators.py", line 7, in <module>
    from pandas.core.dtypes.common import is_bool
  File "C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\PYTHON_SERVICES\lib\site-packages\pandas\core\dtypes\common.py", line 10, in <module>
    from pandas.core.dtypes.dtypes import (

STDERR message(s) from external script:
  File "C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\PYTHON_SERVICES\lib\site-packages\pandas\core\dtypes\dtypes.py", line 16, in <module>
    from .inference import is_list_like
  File "C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\PYTHON_SERVICES\lib\site-packages\pandas\core\dtypes\inference.py", line 9, in <module>
    from pandas.compat import (
ImportError: cannot import name 'Set'

Completion time: 2020-08-25T09:43:23.9780283+02:00

A: I had the same type of issue with the pandas module on SQL Server 2017 with the same ImportError message that you received. The issue surfaced after installing CU22 for SQL Server 2017 recently and was not present when I set up the environment in question about two months earlier.
In my setup of the environment I performed an upgrade of the numpy and pandas modules to the latest available versions for Python 3.5.2 (which is the default Python version included with SQL Server 2017):

*

*numpy:

*

*Pre-installed version: 1.12.1

*Updated version: 1.18.5

*pandas:

*

*Pre-installed version: 0.19.2

*Updated version: 0.24.2

The reason for the upgrades were requirements from other modules (on numpy) and compatiblity issues between pandas and the new numpy version.
After receiving the ImportError error message when doing import pandas, I pinpointed it to line 9-10 in the file:
C:\Program Files\Microsoft SQL Server\MSSQL14.<instance_name>\PYTHON_SERVICES\Lib\site-packages\pandas\core\dtypes
from pandas.compat import (
    PY2, Set, re_type, string_and_binary_types, string_types, text_type)

As I could not find any reason nor any reference from Microsoft on why this should stop working, I did some research and found this post from the pandas Github project:
Missing required dependencies ['numpy'] on pandas 0.24.1 #25316
It seems that there can be issues with old, installed versions of the numpy and pandas modules, even though they are supposed to be removed by pip.exe during the module upgrade/installation process.
Fair enough, I ran repeated uninstalls of the pandas and numpy modules until pip.exe no longer reported any installed versions and the related directories were gone from Lib\site-packages
Set-Location 'C:\Program Files\Microsoft SQL Server\MSSQL14.instance_name\PYTHON_SERVICES\Scripts'
& '.\pip.exe' uninstall pandas # repeated 2 times
& '.\pip.exe' uninstall numpy # repeated 2 times

In both cases, both the updated and some remaining parts of the original versions of the modules were removed.
I then reinstalled both modules and had no issues after that:
& '.\pip.exe' install --upgrade numpy
& '.\pip.exe' install --upgrade pandas


text:
Q: exclude posts without content from search result I have search.php in my WordPress theme, search result is generating fine using The Loop.
What I see is some post don't have content(blank post with title only), and they still appear in search result. Which is quite obvious, but I want only to list post which has some content.
If post don't have any content it should not list in Search Result even if its title has a Search Term.
I believe you won't need to see code to understand my concern. I tried searching for this answer on all known resources, nothing found exactly.
Down vote won't help me.

A: Inside your search loop try adding this:
global $post;
if ( $post->post_content != '' ) {
    // Display this post because it has content.
} else {
    // This post has empty content so do not display it.
}


text:
Q: Помогите с SQL запросом. Нужно правильно отсортировать Не знаю как правильно сделать запрос SQL. Помогите пожалуйста. Есть запрос такого вида:
"SELECT * FROM `user` WHERE `nick` LIKE ?"

при таком запросе выводит все совпадения. Как можно отсортировать правильно и выдать в ответе

*

*Выводить с наименьшего к большему по длине строки

*Вывод начинается с тех букв которые ввели в поиск

A: Если я правильно понял задачу, то так
SELECT
  *
FROM `user`
WHERE `nick` LIKE '%$search%'
ORDER BY length(`nick`), instr(`nick`,  '$search')

A: Ответ, который уже был написан ранее должен работать, но как по мне, лучше использовать не length, а CHAR_LENGTH.
Так мы отсортировали данные по количеству символов, что бы вывод начинался с тех букв, которые ввёл пользователь - просто будем делать поиск именно с тех букв, которые он ввёл:
SELECT *
FROM `user`
WHERE `nick` LIKE '$search%'
ORDER BY CHAR_LENGTH(`nick`)


text:
Q: How to empty Jenkins scheduled job list I'm using Jenkins Rest API to build and schedule job.
The problem that i schedule one job for the Week-end but it execute it several times (Same job executed every minute).
For the rest of the week the job is executed only once, so if there any GUI options to empty the week-end job list ?

A: you can use the following groovy script to clean all ( or part of your queue ....)
this example delete all jobs that start with a specific branch name
import jenkins.model.*

def branchName = build.environment.get("GIT_BRANCH_NAME")

println "=========before clean the queue ... =="

def q = Jenkins.instance.queue
q.items.each {
  println("${it.task.name}:")
}

q.items.findAll { it.task.name.startsWith(branchName) }.each { q.cancel(it.task) }

println "=========after clean the queue ... =="
q = Jenkins.instance.queue
q.items.each {
  println("${it.task.name}:")
}


text:
Q: Convert cURL command to cURL PHP curl -X GET --header "Accept: application/json" --header "authorization: <API token>" "https://api.clashofclans.com/v1/locations"

^  That's the cURL command I want to convert. I tried looking for tutorials on cURL but couldn't understand it. Current code I tried is as follows:
$ch = curl_init('https://api.clashofclans.com/v1/clans/%2399VY9JR8');

curl_setopt($ch,CURLOPT_HTTPHEADER,array('authorization: myToken','Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec($ch);
print_r($result);
curl_close($ch);

Trying to achieve getting response from API and posting then reading them here.

A: In get request you just have to pass the params with the URL itself, following code should work:
$ch = curl_init();
$url = "https://api.clashofclans.com";
$clansId= "2399VY9JR8";
$headers= array("authorization: myToken");
curl_setopt($ch, CURLOPT_URL, $url.'clans/'.$clansId);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
print_r($result);
curl_close($ch);


text:
Q: Invalid attempt to read when no data is present when login access on vb.net I have created a login form in my application. My problem when the login occurred was an error like the title I submitted. my coding as below
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Call DatabaseConnection()
CMD = New SqlCommand("SELECT * FROM UserAplikasi WHERE username = '" + txtUsername.Text + "' AND password = '" + txtUsername.Text + "'", CONN)
RD = CMD.ExecuteReader
If RD.HasRows = True Then
ElseIf RD.Item("HakAkses").ToString = "administrator" Then
    Me.Hide()
    FormMenuUtama.MenuStripFormUtama.Items("HOME").Enabled = True
    FormMenuUtama.MenuStripFormUtama.Items("ORDERPLAN").Enabled = True
    FormMenuUtama.MenuStripFormUtama.Items("FINANCE").Enabled = True
    FormMenuUtama.MenuStripFormUtama.Items("BILLING").Enabled = True
    RD.Close()
ElseIf RD.Item("HakAkses").ToString = "orderplan" Then
    Me.Hide()
    FormMenuUtama.MenuStripFormUtama.Items("HOME").Enabled = True
    FormMenuUtama.MenuStripFormUtama.Items("ORDERPLAN").Enabled = True
    FormMenuUtama.MenuStripFormUtama.Items("FINANCE").Enabled = False
    FormMenuUtama.MenuStripFormUtama.Items("BILLING").Enabled = False
    RD.Close()
ElseIf MsgBox("Username atau Password yang anda masukan salah!") Then
    CONN.Close()
End If

and when I run out with click button login an error

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll
  Additional information: Invalid attempt to read when no data is present.

and I use the user table with the username, password and HakAkses on database sql server. What's wrong ? please. thanks

A: You have been instructed about why there is not data (lack of .Read) and to use parameters and not to store passwords as plain text in comments. I am posting this as an answer because I needed to add a bit of code to demonstrate.
Your If ... ElseIf statement is not making sense. If your reader has rows then your code falls through to the End If. Is that what you want?
    Dim x As Integer = 1
    If x = 1 Then
    ElseIf 1 = 1 Then
        Debug.Print("Second If")
    End If

A: Try using while RD.read instead of If RD.HasRows = True Then. Also, currently your code logic says that if the table has columns, then you don't do anything; if it doesn't then exit code


text:
Q: How Do I Show That a Polynomial Belongs To The Set of $C^ ∞$ functions? How do I show that an $n^ {th}$ degree  polynomial belongs to the set of $C^ ∞$ functions?

A: Prove that the derivative of a polynomial is a polynomial, and the result immediatelly follows.

A: Hint: what is the definition of a $C^\infty$ function? Then, during the proof use induction on $n$.


text:
Q: SJCL CBC Mode not decrypting Using RNCryptor which uses SJCL. I am trying to decrypt a hex message but when using CBC mode, things get weird. Apparently one must declare a beware statement when using CBC and I get an error.
function KeyForPassword(password, salt) {
    console.log("Creating key...");
    var hmacSHA256 = function (password) {
        var hasher = new sjcl.misc.hmac(password, sjcl.hash.sha256);
        this.encrypt = function () {
            return hasher.encrypt.apply(hasher, arguments);
        };
    };
    return sjcl.misc.pbkdf2(password, salt, 10000, 32 * 8, hmacSHA256);
};

function decrypt(password, message, options) {

    message = sjcl.codec.hex.toBits(message);

    options = options || {};

    var version = sjcl.bitArray.extract(message, 0 * 8, 8);
    var options = sjcl.bitArray.extract(message, 1 * 8, 8);

    var encryption_salt = sjcl.bitArray.bitSlice(message, 2 * 8, 10 * 8);
    var encryption_key = _this.KeyForPassword(password, encryption_salt);

    var hmac_salt = sjcl.bitArray.bitSlice(message, 10 * 8, 18 * 8);
    var hmac_key = _this.KeyForPassword(password, hmac_salt);

    var iv = sjcl.bitArray.bitSlice(message, 18 * 8, 34 * 8);

    var ciphertext_end = sjcl.bitArray.bitLength(message) - (32 * 8);
    var ciphertext = sjcl.bitArray.bitSlice(message, 34 * 8, ciphertext_end);

    var hmac = sjcl.bitArray.bitSlice(message, ciphertext_end);
    var expected_hmac = new sjcl.misc.hmac(hmac_key).encrypt(sjcl.bitArray.bitSlice(message, 0, ciphertext_end));

    // .equal is of consistent time
    if (! sjcl.bitArray.equal(hmac, expected_hmac)) {
      throw new sjcl.exception.corrupt("HMAC mismatch or bad password.");
    }

    var aes = new sjcl.cipher.aes(encryption_key);
    sjcl.beware["CBC mode is dangerous because it doesn't protect message integrity."]()
    var decrypted = sjcl.mode.cbc.decrypt(aes, ciphertext, iv);

    return decrypted.toString(CryptoJS.enc.Utf8);
};

Everything matches the encryption on the  Python side in terms of salts, keys, and the hashes. But I get this error:
TypeError: Cannot read property 'CBC mode is dangerous because it doesn't protect message integrity.' of undefined

I'm thought the method is deprecated so I then tried to use this CryptoJS method:
var decrypted = CryptoJS.AES.decrypt(ciphertext, encryption_key, {iv:iv});

This just returned a blank string.
I feel like I am really close, just need some help on this last part, thanks.

A: SJCL
CBC is not included in the prebuilt sjcl.js if you look into configure on GitHub. You have to include the CBC file (core/cbc.js) separately in your page or you would need to manipulate configure file to add cbc in that list of enabled modules.
CryptoJS
decrypted isn't a blank string. CryptoJS.<cipher>.decrypt() returns a WordArray object with a negative number of sigBytes. This property denotes the number of bytes that the WordArray is expected to contain. A negative number means that something went wrong. It doesn't always have to be a negative number.
There can be a number of problems:

*

*You don't have the correct key.

*You don't have the a properly sliced ciphertext.

*The ciphertext is not an OpenSSL formatted string or not a CipherParams object. Try to pass {ciphertext: ciphertext} instead.

*The key and IV are not correctly formatted: they should be WordArray objects.

A: As Artjom B. stated, cbc.js is needed as well as bitArray.js (necessary part of the decryption and something I was missing). The original code works fine now.
As an aside on the PBKDF2 iteration count as Rob Napier pointed out, it's slow. For this case (decryption), however, the 10K count worked quickly, but for encryption, I supplemented the kdf with CryptoJS's PBKDF2 at 1000 iterations instead (was getting bitArray error with sjcl's).


text:
Q: React js. Как добавить сообщение о удалении? Всем привет, мне нужно добавить алерт на удаление заметки, как я это могу сделать? Спасибо за ответы!
это код заметок
'export const Notes = ({notes, onRemove}) =>
<TransitionGroup component={'ul'} className='list-group'>
{notes.map(note => (
<CSSTransition
key={note.id}
classNames={'note'}
timeout={500}
>

{note.title}
{note.date}

<button
type='button'
className='btn btn-outline-danger btn-sm'
onClick={() => onRemove(note.id)}
>
×
</button>

</CSSTransition>
))}
</TransitionGroup>

'
Это логика вызова алерта
'export const Form = () => {
const [value, setValue] = useState('')
const alert = useContext(AlertContext)
const firebase = useContext(FirebaseContext)
const submitHandler = event => {
event.preventDefault()
if(value.trim()) {
firebase.addNote(value.trim()).then(() => {
alert.show('Заметка была созданна', 'success')
}).catch(() => {
alert.show('Что-то пошло не так', 'danger')
})
setValue('')
} else {
alert.show('Введите название заметки')
}
}
return (
<form onSubmit={submitHandler}>

<input
type='text'
className='form-control'
placeholder='Введите название заметки'
value={value}
onChange={e => setValue(e.target.value)}
/>

</form>
)
}'


text:
Q: Capybara feature specs fails with Turbo Drive I'm experimenting with introducing Turbo Drive on a couple of pages in my Rails 6.1 app.
Ḯ've got it as expected after moving some legacy JQuery plugin initialization from $(document).ready() calls into document.addEventListener('turbo:load', ..) calls.
When I'm running my Capybara feature specs, however, I can see from the screenshots of the failing specs like the JQuery plugins have not been initialized like they should. One typical example of a test that is failing :
scenario 'element is visible', :js do
  visit(my_page_path)
  expect(page.find(#some-jquery-plugin-created-element).text).to \
         eq 'some expected text from the plugin element'
end

Can anyone help me understand why this is not working in the feature specs? It looks to me like the turbo:load event is not getting triggered at all.

What I've tried
Checking the browser logs
I enabling logging in the driver:
Selenium::WebDriver::Remote::Capabilities.chrome( "goog:loggingPrefs": { browser: 'ALL' } ).
.. but calling page.driver.browser.manage.logs.get(:browser) just before the failing expect call just returns an empty array.
Perhaps I'm doing it wrong?
Making sure Capybara doesn't time out before the page finishes loading
Capybara.default_max_wait_time = 10

A: By writing your expectations like
expect(page.find(#some-jquery-plugin-created-element).text).to \
         eq 'some expected text from the plugin element'

you are defeating Capybaras retry functionality which will lead to lots of failing tests in dynamic pages.  You should "never" use the basic RSpec matchers (eq, etc) with Capybara related objects.
In your case the find call is waiting for a matching element to exist, then getting its text and checking it. This will fail because when the element is first added to the page it may not yet have its full text contents. Instead you should be using the Capybara provided matchers which will use Capybaras waiting behavior for things to match
expect(page.find(#some-jquery-plugin-created-element)).to have_text('some expected text from the plugin element')


text:
Q: Filter Columns in a Table based on Data Type Table name:  Table1
Name             DataType
PK_tablekey        INT
FK_Table2Keu       INT
CreateTime       datetime
DateField1       datetime
DateField2       datetime
Createdby        NVARCHAR(32)
Name1             NVARCHAR(32)
Flag             BIT
Value1           Decimal(19,4)
Value2           Decimal(19,4)

I want to query only these field out of that using over by clause
DateField1       datetime
DateField2       datetime
Name1            NVARCHAR(32)
Flag             BIT
Value1           Decimal(19,4)
Value2           Decimal(19,4)

Query:
SELECT
    (ROW_NUMBER() OVER (ORDER BY ORDINAL_POSITION ASC)) AS ColumnNumber,
    CAST(COLUMN_NAME AS NVARCHAR(150)) AS ColumnName
FROM
    INFORMATION_SCHEMA.COLUMNS
WHERE
    TABLE_NAME = N'Table1'
    AND DATA_TYPE IN ( N'decimal')

UNION ALL

SELECT
    (ROW_NUMBER() OVER (ORDER BY ORDINAL_POSITION ASC)) AS ColumnNumber,
    CAST(COLUMN_NAME AS NVARCHAR(150)) AS ColumnName
FROM
    INFORMATION_SCHEMA.COLUMNS
WHERE
    TABLE_NAME = N'Table1'
    AND DATA_TYPE IN (N'nvarchar')
    AND COLUMN_NAME = 'Name1 '

UNION ALL

SELECT
    (ROW_NUMBER() OVER (ORDER BY ORDINAL_POSITION ASC)) AS ColumnNumber,
    CAST(COLUMN_NAME AS datetime) AS ColumnName,
    CAST(COLUMN_NAME AS datetime) AS OverwriteColumnName
FROM
    INFORMATION_SCHEMA.COLUMNS
WHERE
    TABLE_NAME = N'Table1'
    AND DATA_TYPE IN (N'datetime')
    AND COLUMN_NAME IN ('DateField1', 'DateField2')

It does not seem to work when this proc is called it throws an error message

Request failed: Invalid column name : DateField1
  Request failed: Invalid column name: DateField2

Also I want to add the BIT column as well .
Can anyone help me would be nice if the query is short  as i use the UNION ALL.

A: Why not do this?
SELECT ROW_NUMBER() OVER (PARTITION BY DATA_TYPE ORDER BY ORDINAL_POSITION ASC) AS ColumnNumber,
       CAST(COLUMN_NAME AS NVARCHAR(150)) AS ColumnName
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'Table1' AND
      DATA_TYPE IN ( N'decimal', N'datetime', N'Name1') ;

Instead of DATA_TYPE, you might want to specify the columns that you do want.  The key idea is PARTITION BY.

A: As you use rownumber, its SQL Server.
First, your query has errors: all unions must have same columns to be returned. Your 3rd union returns 3 columns instead of required two.
If you need to order your data, you can try this:
SELECT
     [ColumnNumber]
    ,[ColumnName]
FROM
(
    SELECT
         [ColumnNumber] = (ROW_NUMBER() OVER (ORDER BY ORDINAL_POSITION ASC))
        ,[ColumnName]   = CAST(COLUMN_NAME AS NVARCHAR(150))
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_NAME = N'Table1'
        AND DATA_TYPE IN ( N'decimal')

    UNION ALL

    SELECT
         [ColumnNumber] =  (ROW_NUMBER() OVER (ORDER BY ORDINAL_POSITION ASC))
        ,[ColumnName]   =  CAST(COLUMN_NAME AS NVARCHAR(150))
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_NAME = N'Table1'
        AND DATA_TYPE IN (N'Name1')
        AND COLUMN_NAME = 'Name1 '

    UNION ALL

    SELECT
         [ColumnNumber] = (ROW_NUMBER() OVER (ORDER BY ORDINAL_POSITION ASC))
        ,[ColumnName]   =  CAST(COLUMN_NAME AS datetime)
        --  , CAST(COLUMN_NAME AS datetime) AS OverwriteColumnName  --you need 2 cols, not 3!
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_NAME = N'Table1'
        AND DATA_TYPE IN (N'datetime')
        AND COLUMN_NAME IN ('DateField1','DateField2')
) AS [r]
ORDER BY
     [r].[ColumnNumber]
    ,[r].[ColumnName];


text:
Q: NHibernate many-to-many criteria creating multiple database calls I have Events, which can have many EventTypes.  I'm attempting to query the database by using the NHibernate mappings I have defined.  The issue is that when defining criteria on child objects, NHibernate makes repeated calls to the database, rather than making one call for all the data it needs.  This leads to an extremely slow search.
The database tables are as follows:
Event
-EventID

EventType
-EventTypeID

EventEventTypeID
-EventEventTypeID
-EventID
-EventTypeID

The Event class looks like this:
Id as Integer
Types as IList(Of EventType)

The EventType class looks like this:
Id as Integer
FullTitle as String

There is no EventEventType class.
The NHibernate mappings are as follows:
EventMapping
Table("event.Event")
Id(Function(x) x.Id).Column("EventID").GeneratedBy().Identity()
HasManyToMany(Of EventType)(Function(x) .Types).Table("event.EventEventType").ParentKeyColumn("EventID").ChildKeyColumn("EventTypeID").Cascade.All()

EventTypeMapping
Table("event.EventType")
Id(Function(x) x.Id).Column("EventTypeID").GeneratedBy().Identity()
Map(Function(x) x.FullTitle).Column("EventTypeFullTitle")

On the open of my form, the following function is called, which sets the FetchMode for the Types property of Event.
Public Function CreateListViewQuery(currentNHibernateSession As ISession) As NHibernate.ICriteria Implements IListViewQueryable.CreateListViewQuery

        Return currentNHibernateSession.CreateCriteria(Of [Event])().SetFetchMode("Types", FetchMode.Join)

End Function

This is used to populate the listview, which happens extremely quickly, with just one call to the database for all the data:
SELECT TOP (50)
    this_.EventID as EventID
    , t3_.EventTypeID as EventTyp1_15_0_
    , t3_.EventTypeFullTitle as EventTyp2_15_0_
FROM event.Event this_
    inner join event.EventEventType types5_ on this_.EventID=types5_.EventID
    inner join event.EventType t3_ on types5_.EventTypeID=t3_.EventTypeID

However, when I add a Criterion.Expression, like this (where QuickSearch is my user input):
.CreateAlias("Types", "t", NHibernate.SqlCommand.JoinType.InnerJoin)
.Add(NHibernate.Criterion.Expression.Like("t.FullTitle", QuickSearch))

I get 1 call which looks like this:
SELECT TOP 50
    this_.EventID as EventID12_6_
    , types8_.EventID as EventID
    , t3_.EventTypeID as EventTyp2_
    , t3_.EventTypeFullTitle as EventTyp2_15_0_
FROM
    event.Event this_
        inner join event.EventEventType types8_ on this_.EventID=types8_.EventID
        inner join event.EventType t3_ on types8_.EventTypeID=t3_.EventTypeID
WHERE t3_.EventTypeFullTitle like @p1

And 50 more calls which look like this (50 as I have selected TOP 50):
SELECT
    types0_.*
FROM
    event.EventEventType types0_
        left outer join event.EventType eventtype1_ on types0_.EventTypeID=eventtype1_.EventTypeID
WHERE types0_.EventID=@p0

(where @p0 is each of the TOP 50 Events which are returned by the search)
I feel like only the first call should be necessary for this.
Is it the nature of a many-to-many relationship which means NHibernate needs these additional calls?  Is there something in my mapping which I've missed?
Perhaps importantly, I have used exactly the same technique for String properties of Event, and one-to-many relationships from Event and only one call is required for the search.  The problem seems to only exist with many-to-many relationships.
Apologies for the long question, and thank you for getting this far.  I've read many questions on a similar topic but couldn't find any addressing the issues of repeated database calls for many-to-many relationships.

A: What you are describing is an nHibernate n+1 issue (basically the number of queries executed is in direct proportion to the result set size), which can be difficult to resolve depending on how complex your query is.
Although not an obvious solution what has worked for me in the past is to change the join type to left outer join as below:
.CreateAlias("Types", "t", NHibernate.SqlCommand.JoinType.LeftOuterJoin)


text:
Q: Choosing my ending in GTA 5 I have a lot of different autosaves...

...and it autosaved right after I chose to  kill Trevor.

I want to know if I can access my other autosaves so I can retry it. I have already tried going back to a older save and it hasn't worked. Any ideas?

A: Assuming that you picked the ending that you wanted, you can replay the other two options.
Navigate the start menu to the replay option, scroll to the bottom, and you should see the following 3 missions:

*

*Something Sensible (Option A)

*The Time's Come (Option B)

*The Third Way (Option C)
Note: The stuff in the parentheses won't be there, I added that.
If you wanted to change the outcome of your end game, you would need to load another save sometime before the final mission.  If you don't have one, then you'll have to start a new game to change the end out come.


text:
Q: Add custom localized text in DateTimeFormatter, for a new custom TemporalField I've created a CENTURY field that implements java.time.temporal.TemporalField - this question is not focusing on the correct implementation details of such field (which will be handled later), I'm interested in the DateTimeFormatter issue as explained below.
Basically, the field gets the ChronoField.YEAR of a temporal object and uses this value to calculate the century (the calculation is made in getFrom(TemporalAccessor temporal) method, considering that the 1st century is from year 1 to 100 - but as I said, let's not stick too much in these details).
The most basic usage is:
LocalDate.of(2017, 1, 1).get(CENTURY); // 21

Which returns 21 in this case.
The field can also be used in a DateTimeFormatter:
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
    .appendPattern("dd/MM/yyyy ")
    .appendValue(CENTURY)
    .toFormatter();

System.out.println(fmt.format(LocalDate.of(2017, 1, 1))); // 01/01/2017 21

The output for the above is:

01/01/2017 21

But what I want to do is to use a custom localized text for this field. If I create a formatter like this:
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
    .appendPattern("dd/MM/yyyy ")
    // century text
    .appendText(CENTURY, TextStyle.SHORT)
    // use English locale
    .toFormatter(Locale.ENGLISH);

System.out.println(fmt.format(LocalDate.of(2017, 1, 1))); // 01/01/2017 21

Since there's no localized data for my new CENTURY field, the text is only its own value 21.
I'm trying to find a way to add custom localized strings for this field, like it's done with month and day of week, for example (let's assume that I already have the resource bundle properties files set).
Checking the source code, I've found that the formatter internally uses a TextPrinterParser, which in turn uses a DateTimeTextProvider to get the localized strings, but none of those classes are public and can't be used nor extended. And the API doesn't seem to provide a way to add custom localized strings for new fields.
I could do it only by using reflection and a java.lang.reflect.Proxy to overwrite the behaviour of the TextPrinterParser, but I wonder if there's a better way (that doesn't require all this "magic").
How can this be done (if possible)?

I know I could also use appendText(TemporalField field, Map<Long,String> textLookup), but that wouldn't be a "locale sensitive" solution (although it seems to be the best workaround available).

A: This is not possible in java.time.* today. The DateTimeTextProvider class was intended to be extensible, but this got descoped during development. Providing pluggable text providers would be a useful enhancement to Java.


text:
Q: Kohana and ExtJS or JQuery for Intranet In the process of building an intranet. We have lots of tables and data to show/edit/review and I want the most functional solution.
I like the extjs widgets and since I am only creating an in-house solution, I believe the licensing allows me to use it without paying.
Anyone with some opinion on the best way forward on this? I would really appreciate it.

A: Netzpirat's answer is misleading.
  The GNU GPL v3 license requires you to distribute the source code with any release of the software. Web based applications aren't distributed in the traditional way that GPL assumes, so FSF modified the license to include "conveyance", which is debatable whether it ever really applies.
  If conveyance does not apply, you're home free.
  In the event that conveyance would apply, the software is restricted in this case to inhouse employees and from a licensing point of view, they would be acting for the company and not be entitled to the source code.
  The GPL is specifically designed to allow for inhouse usage of GPL'd software -- e. g. the GCC suite, without requiring distribution of modifications so long as the modified software is not distributed, but kept inhouse.
In summary, you're quite right in assuming you'll be able to use the library under the GPL v3 license.

A: Ext JS is tripple licensed under

*

*Sencha Commercial License for applications whose source code you want to keep proprietary.

*Sencha Commercial OEM License if you want to use Ext JS to create your own commercially licensed SDK.

*GNU GPL license v3 for developing open source software.

You have to buy the first two license types, only the GPL 3 licensed framework is for free.
It doesn't depend if you build a public application or an in-house application, it depends whether you make your application open source or not.
So when you don't want to pay, it's not legal to use it in an in-house application.
You can read more at the Ext JS licensing page.

A: Sencha, Inc. (Ext.js) now provides its definition of "conveyance", which is really the part of the GPL that concerns the delivery of Javascript to a user to be exectued, on its FAQ page under the heading "What is Sencha's interpretation of "conveyance" under the GPL v3?"  In part, Sencha asserts:

Since Ext JS, Sencha GXT and Sencha Touch are software programs that can run within the browser while disconnected from the network or the rest of a server program; when a Sencha based interface is embedded in a web-page served to a user who does not have an employee relationship with the original licensed entity, we consider that "conveyance" rather than simple web page "propagation" as defined by the GPL v3 has occurred, and the source code of the whole application must be provided to the user.

http://www.sencha.com/legal/open-source-faq/
Because your users would all have "an employee relationship with the original licensed entity," Sencha seems to agree with zrvan that it is acceptable not to license the entire the project under the GPL.  Furthermore, this is only Sencha's interpretation of conveyance, which may not reflect how a court would interpret it.  At least you can feel somewhat comfortable knowing that you're in compliance with the author's definition.


text:
Q: What does pooled variance "actually" mean? I am a noob in statistics, so could you guys please help me out here.
My question is the following: What does pooled variance actually mean?
When I look for a formula for pooled variance in the internet, I find a lot of literature using the following formula (for example, here: http://math.tntech.edu/ISR/Mathematical_Statistics/Introduction_to_Statistical_Tests/thispage/newnode19.html):
\begin{equation} \label{eq:stupidpooledvar}
\displaystyle S^2_p = \frac{S_1^2 (n_1-1) + S_2^2 (n_2-1)}{n_1 + n_2 - 2}
\end{equation}
But what does it actually calculate? Because when I use this formula to calculate my pooled variance, it gives me wrong answer.
For example, consider these "parent sample":
\begin{equation} \label{eq:parentsample}
2,2,2,2,2,8,8,8,8,8
\end{equation}
The variance of this parent sample is $S^2_p=10$, and its mean is $\bar{x}_p=5$.
Now, suppose I split this parent sample into two sub-samples:

*

*The first sub-sample is 2,2,2,2,2 with mean $\bar{x}_1=2$ and variance $S^2_1=0$.

*The second sub-sample is 8,8,8,8,8 with mean $\bar{x}_2=8$ and variance $S^2_2=0$.

Now, clearly, using the above formula to calculate the pooled/parent variance of these two sub-samples will produce zero, because $S_1=0$ and $S_2=0$. So what does this formula actually calculate?
On the other hand, after some lengthy derivation, I found the formula which produces the correct pooled/parent variance is:
\begin{equation} \label{eq:smartpooledvar}
\displaystyle S^2_p = \frac{S_1^2 (n_1-1) + n_1 d_1^2 + S_2^2 (n_2-1) + n_2 d_2^2} {n_1 + n_2 - 1}
\end{equation}
In the above formula, $d_1=\bar{x_1}-\bar{x}_p$ and $d_2=\bar{x_2}-\bar{x}_p$.
I found a similar formula with mine, for example here: http://www.emathzone.com/tutorials/basic-statistics/combined-variance.html
 and also in Wikipedia. Although I have to admit that they don't look exactly the same like mine.
So again, what does pooled variance actually mean? Shouldn't it mean the variance of parent sample from the two sub-samples? Or I am completely wrong here?
Thank you in advance.

EDIT 1: Someone says that my two sub-samples above are pathological since they have zero variance. Well, I could give you a different example. Consider this parent sample:
\begin{equation} \label{eq:parentsample2}
1,2,3,4,5,46,47,48,49,50
\end{equation}
The variance of this parent sample is $S^2_p=564.7$, and its mean is $\bar{x}_p=25.5$.
Now, suppose I split this parent sample into two sub-samples:

*

*The first sub-sample is 1,2,3,4,5 with mean $\bar{x}_1=3$ and variance $S^2_1=2.5$.

*The second sub-sample is 46,47,48,49,50 with mean $\bar{x}_2=48$ and variance $S^2_2=2.5$.

Now, if you use "literature's formula" to compute the pooled variance, you will get 2.5, which is completely wrong, because the parent/pooled variance should be 564.7. Instead, if you use "my formula", you will get correct answer.
Please understand, I use extreme examples here to show people  that the formula indeed wrong. If I use "normal data" which doesn't have a lot of variations (extreme cases), then the results from those two formulae will be very similar, and people could dismiss the difference due to rounding error, not because the formula itself is wrong.

A: Put simply, the pooled variance is an (unbiased) estimate of the variance within each sample, under the assumption/constraint that those variances are equal.
This is explained, motivated, and analyzed in some detail in the Wikipedia entry for pooled variance.
It does not estimate the variance of a new "meta-sample" formed by concatenating the two individual samples, like you supposed. As you have already discovered, estimating that requires a completely different formula.

A: Pooled variance is used to combine together variances from different samples by taking their weighted average, to get the "overall" variance. The problem with your example is that it is a pathological case, since each of the sub-samples has variance equal to zero. Such pathological case has very little in common with the data we usually encounter, since there is always some variability and if there is no variability, we don't care about such variables since they carry no information. You need to notice that this is a very simple method and there are more complicated ways of estimating variance in hierarchical data structures that are not prone to such problems.
As about your example in the edit, it shows that it is important to clearly state your assumptions before starting the analysis. Let's say that you have $n$ data points in $k$ groups, we would denote it as $x_{1,1},x_{2,1},\dots,x_{n-1,k},x_{n,k}$, where the $i$-th index in $x_{i,j}$ stands for cases and $j$-th index stands for group indexes. There are several scenarios possible, you can assume that all the points come from the same distribution (for simplicity, let's assume normal distribution),
$$
x_{i,j} \sim \mathcal{N}(\mu, \sigma^2) \tag{1}
$$
you can assume that each of the sub-samples has its own mean
$$
x_{i,j} \sim \mathcal{N}(\mu_j, \sigma^2) \tag{2}
$$
or, its own variance
$$
x_{i,j} \sim \mathcal{N}(\mu, \sigma^2_j) \tag{3}
$$
or, each of them have their own, distinct parameters
$$
x_{i,j} \sim \mathcal{N}(\mu_j, \sigma^2_j) \tag{4}
$$
Depending on your assumptions, particular method may, or may not be adequate for analyzing the data.
In the first case, you wouldn't be interested in estimating the within-group variances, since you would assume that they all are the same. Nonetheless, if you aggregated the global variance from the group variances, you would get the same result as by using pooled variance since the definition of variance is
$$
\mathrm{Var}(X) = \frac{1}{n-1} \sum_i (x_i - \mu)^2
$$
and in pooled estimator you first multiply it by $n-1$, then add together, and finally divide by $n_1 + n_2 - 1$.
In the second case, means differ, but you have a common variance. This example is closest to your example in the edit. In this scenario, the pooled variance would correctly estimate the global variance, while if estimated variance on the whole dataset, you would obtain incorrect results, since you were not accounting for the fact that the groups have different means.
In the third case it doesn't make sense to estimate the "global" variance since you assume that each of the groups have its own variance. You may be still interested in obtaining the estimate for the whole population, but in such case both (a) calculating the individual variances per group, and (b) calculating the global variance from the whole dataset, can give you misleading results. If you are dealing with this kind of data, you should think of using more complicated model that accounts for the hierarchical nature of the data.
The fourth case is the most extreme and quite similar to the previous one. In this scenario, if you wanted to estimate the global mean and variance, you would need a different model and different set of assumptions. In such case, you would assume that your data is of hierarchical structure, and besides the within-group means and variances, there is a higher-level common variance, for example assuming the following model
$$
\begin{align}
x_{i,j} &\sim \mathcal{N}(\mu_j, \sigma^2_j) \\
\mu_j &\sim \mathcal{N}(\mu_0, \sigma^2_0)  \\
\sigma^2_j &\sim \mathcal{IG}(\alpha, \beta)
\end{align} \tag{5}
$$
where each sample has its own means and variances $\mu_j,\sigma^2_j$ that are themselves draws from common distributions. In such case, you would use a hierarchical model that takes into consideration both the lower-level and upper-level variability. To read more about this kind of models, you can check the Bayesian Data Analysis book by Gelman et al. and their eight schools example. This is however much more complicated model then the simple pooled variance estimator.

A: Through pooled variance we are not trying to estimate the variance of a bigger sample, using smaller samples. Hence, the two examples you gave don't exactly refer to the question.
Pooled variance is required to get a better estimate of population variance, from two samples that have been randomly taken from that population and come up with different variance estimates.
Example, you are trying to gauge variance in the smoking habits of males in London. You sample two times, 300 males from London. You end up getting two variances (probably a bit different!). Now since, you did a fair random sampling (best to your capability! as true random sampling is almost impossible), you have all the rights to say that both the variances are true point estimates of population variance (London males in this case).
But how is that possible? i.e. two different point estimates!! Thus, we go ahead and find a common point estimate which is pooled variance. It is nothing but weighted average of two point estimates, where the weights are the degree of freedom associated with each sample.
Hope this clarifies.

A: The problem is if you just concatenate the samples and estimate its variance you're assuming they're from the same distribution therefore have the same mean. But we are in general interested in several samples with different mean. Does this make sense?

A: The use-case of pooled variance is when you have two samples from distributions that:

*

*may have different means, but

*which you expect to have an equal true variance.

An example of this is a situation where you measure the length of Alice's nose $n$ times for one sample, and measure the length of Bob's nose $m$ times for the second. These are likely to produce a bunch of different measurements on the scale of millimeters, because of measurement error. But you expect the variance in measurement error to be the same no matter which nose you measure.
In this case, taking the pooled variance would give you a better estimate of the variance in measurement error than taking the variance of one sample alone.

A: Although I am very late to the conversation maybe I can add something helpful:
It seems to me that the OP wants to know why (what for) we would need a pooled variability estimate $\hat\sigma_{pooled}$ as a weighted average of two samples (be it variance or standard deviation).
As far as I am aware the main practical need for this kind of dispersion measure arises from wanting to compare means of (sub-)groups: so if I want to compare the average nose length for 1) people who did not undergo a gene therapy, 2) people who underwent gene therapy A and 3) people who underwent gene therapy B.
To be better able to compare the amount of the mean differences in length (mm) I divide the mean difference, say, $e=\bar x_{Control}-\bar x_{GTA}=30mm-28mm=2mm$ by the variability estimate (here standard deviation). Depending on the size of the square root of pooled variance (pooled standard deviation) we can better judge the size of the 2mm difference between those groups (e.g., $d=2mm/0.5mm=4$ vs. $d=2mm/4mm=0.5$ --> Does gene therapy A do something to the nose length? And if so, how much? When $d=4$ or $2 \pm 0.5mm$ there seems to be a "stable" or "consistent" or "big" (compared to the variability) difference between the mean nose lengths, when $d=0.5$ or  $2 \pm 4mm$ it does not seem so much, relatively speaking. In case all values within both groups are the same and therefore there is no variability within the groups, $d$ would not be defined but the interpretation would be $2 \pm 0mm=2mm$ exactly).
This is the idea of effect size (first theoretically introduced by Neyman and Pearson as far as I know, but in one kind or another used well before, see Stigler, 1986, for example).
So what I am doing is comparing the mean difference between groups with the mean differences within those same groups, i.e weighted average of variances (standard deviations). This makes more sense than to compare the mean difference between (sub-)groups with the mean difference within the "whole" group, because, as you (Hanciong) have shown, the variance (and standard deviation) of the whole group contains the difference(s) of the group means as well.
The theoretical need for the measure arises from being able to use the $t$-distribution to find the probability for the observed mean difference or a more extreme one, given some expected value for the mean difference (p-value for e.g., Null-Hypothesis-Significance-Test, NHST, or Neyman-Pearson hypothesis test or Fisher hypothesis test, confidence intervals etc.): $p(e \ge e_{observed}|\mu_e=0)$.
As far as I know the p-value obtained by the $t$-distribution (and especially the $F$-distribution in cases with more than 2 means to compare) will give correct estimates for the probability only when both (or all) samples are drawn from populations with equal variances (homogeneity of variance, as pointed out in the other answers already; this should be described in (more) detail in most statistics textbooks). I think all distributions based on the normal distribution ($t$, $F$, $\chi^2$) assume a variance of more than 0 and less than $\infty$, so it would be impossible to find the p-value for a case with a within variability of 0 (in this case you would obviously not assume to have drawn your sample from a normal distribution).
(This also seems intuitively reasonable: if I want to compare two or more means then the precision of those means should be the same or at least comparable:
if I run my gene therapy A on people whose nose lengths are quite similar, say $\bar x \pm 0.5mm$ but have a group of people with high variability in nose lengths in my control group, say $\bar x \pm 4mm$ it doesn't seem fair to directly compare those means, because those means do not have the same "mean-meaning"; in fact the very much higher variance/standard deviation in my control group could be indicating further subgroups, maybe differences of nose lengths due to differences on some gene.)


text:
Q: Format currency with indian suffixes IOS I want to display the number 13456 as 13.456K,3456789 as 34.56L.Is there any formatter in IOS to convert with K(thousand),L(Lakh),M(Million),C(Crore) suffixes?

A: There's no library or sdk in iOS for shortening or converting currency using abbreviations like K (thousand), M (million) similarly L (100 thousand), C (10 million), etc., as these abbreviations are different in different countries and regions.
You'll have to convert the number according to category in which your number falls and using NSNumberFormatter with NSNumberFormatterCurrencyStyle you can format your number according to your requirement.
You can use following code for converting currency amount according to your requirement:
float shortenedAmount = actualAmount;
NSString *suffix = @"";
if(currency >= 10000000.0f) {
    suffix = @"C";
    shortenedAmount /= 10000000.0f;
}
else if(currency >= 1000000.0f) {
    suffix = @"M";
    shortenedAmount /= 1000000.0f;
}
else if(currency >= 100000.0f) {
    suffix = @"L";
    shortenedAmount /= 100000.0f;
}
else if(currency >= 1000.0f) {
    suffix = @"K";
    shortenedAmount /= 1000.0f;
}

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:shortenedAmount]];

NSString *requiredString = [NSString stringWithFormat:@"%@%@", numberAsString, suffix];

A: IOS does not provide any formatter for those suffix.

You can make your own formatter using extension. Extensions will add new functionality to your program and it would definitely work :)

Link to extensions.

A: Please try below custom method -
 -(NSString *)stringFormating:(int)numValue
{
    NSString *valueString = [NSString stringWithFormat:@"%d", numValue];

    if ([valueString length]>7)
    {
        NSString *strsecondPart= [valueString substringFromIndex:[valueString length] -7];

        return [NSString stringWithFormat:@"%@.%dC",[valueString substringToIndex:[valueString length] -7],[strsecondPart intValue]];

    }
    else if ([valueString length]>5)
    {

        NSString *strsecondPart= [valueString substringFromIndex:[valueString length] -5];

        return [NSString stringWithFormat:@"%@.%dL",[valueString substringToIndex:[valueString length] -5],[strsecondPart intValue]];

    }
    else if ([valueString length]>3)
    {

        NSString *strsecondPart= [valueString substringFromIndex:[valueString length] -3];

        return [NSString stringWithFormat:@"%@.%dK",[valueString substringToIndex:[valueString length] -3],[strsecondPart intValue]];

    }

    return valueString;

}

NSLog(@"%@", [self stringFormating:100000]);

output will be 1.0L
NSLog(@"%@", [self stringFormating:123456]);

output will be 1.23456L

A: Here is the Swift implementation:
Convert NumberFormatter (NSNumberFormatter) in Swift to Make Currency in Indian Numbering Format.
extension Int {
        func withCommas() -> String {
            let numberFormatter = NumberFormatter()
            numberFormatter.numberStyle = .decimal
           numberFormatter.locale = Locale(identifier: "en_IN")      // English (Indian) locale with english language is used
            return numberFormatter.string(from: NSNumber(value:self))!
        }
    }

//Easy to use:--
            let strValue = "64567890"
            let intValue = (strValue! as NSString).integerValue
            print(intValue.withCommas())                   // 6,45,67,890
//             cell.lbl.text = intValue.withCommas()


text:
Q: How to add a checkbox into a table     function addRow() {
    var a = document.getElementById("modulename").value;
    var b = document.getElementById("duedate").value;
    var c = document.getElementById("duetime").value;
    var d = document.getElementById("worktype").value;
    var e = document.getElementById("notes").value;
    //var f = <input type="checkbox" id="complete" value="no">
    var table = document.getElementById("myTable");
    var row = table.insertRow(1);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
    var cell4 = row.insertCell(3);
    var cell5 = row.insertCell(4);
    //var cell6 = row.insertCell(5);
    cell1.innerHTML = a;
    cell2.innerHTML = b;
    cell3.innerHTML = c;
    cell4.innerHTML = d;
    cell5.innerHTML = e;
    //cell6.innerHTML = e;
    //document.getElementById("myTable").innerHTML = x;

I've commented the checkbox part of the code out for now as it wasn't functioning before hand, new to HTML, any help is appreciated.
I've been stuck at it for an hour or two now and just can't figure out whats wrong.

A: You could do it as the same way you were doing but within '' as below:
var f = '<input type="checkbox" id="complete" value="no">';

and then
cell6.innerHTML=f

A: Since at this point your element is just a string literal, you need to put it in quotation marks:
var f = '<input type="checkbox" id="complete" value="no">';

I'm using single quotes here, because the string already contains double quotes. Otherwise, you would have to escape them:
var f = "<input type=\"checkbox\" id=\"complete\" value=\"no\">";


text:
Q: Call a derived class' (non-virtual) function in the base class' Destructor Suppose we have the following class template:
template<typename T>
class Object
{
public:
    Object() = default;
    Object(const Object&) = delete;
    Object(Object&& other) noexcept
    {
        if (this != &other)
        {
            static_cast<T*>(this)->Release();
            m_Id = std::exchange(other.m_Id, 0);
        }
    }

    auto operator=(const Object&) = delete;
    Object& operator=(Object&& other) noexcept
    {
        if (this != &other) {
            static_cast<T*>(this)->Release();
            m_Id = std::exchange(other.m_Id, 0);
        }

        return *this;
    }

    ~Object()
    {
        static_cast<T*>(this)->Release();
        m_Id = 0;
    }

protected:
    std::uint32_t m_Id;
};

(Please ignore the duplication in the move constructor and move assignment operator for the moment)
This class is meant to act as a base class for OpenGL object wrappers. Following is an example use:
class VertexBuffer : public Object<VertexBuffer>
{
public:
    VertexBuffer()
    {
        glGenBuffers(1, &m_Id);
        ...
    }

    void Release()
    {
        glDeleteBuffers(1, &m_Id);
    }
};

The Object<T> class template is supposed to take care of the bookkeeping.
The reason for doing this is that the pattern in the Object<T> class is repeated the exact same way for (almost) every OpenGL object wrapper that might be written. The only difference is the creation and deletion of the objects which is handled by the constructor and the Release() function in this example.
Now the question is whether this (Object<T>::~Object() to be specific) taps into UB land? Undefined Behavior Sanitizer doesn't report any errors but I've never done this, so I though of asking people with more experience to make sure.

A: Don't do that. That'll cause an undefined behavior.
Instead, implement the template class as a derived class, like the following example.
class BufferGrandBase {
protected:
    GLuint id;
};

template<class B>
class Buffer : public B {
public:
    Buffer() {
        B::Create();
    }
    ~Buffer() {
        B::Destroy();
    }
};

class VertexBufferBase : public BufferGrandBase {
public:
    void Create() { glGenBuffers(1, &id); }
    void Destroy() { glDeleteBuffers(1, &id); }
};
typedef Buffer<VertexBufferBase> VertexBuffer;

This pattern will also simplify implementing constructors and operators.

A: Short answer: Yes, this is undefined behaviour, don't do that.
Long answer:
The destruction of VertexBuffer invokes first ~VertexBuffer() and then invokes ~Object<VertexBuffer>() afterwards. When ~Object<VertexBuffer>() is invoked the VertexBuffer "part" of the object has already been destroyed, i.e. you are now doing an illegal downcast via static_cast (the remaining valid part of the object is a Object<VertexBuffer>, not a VertexBuffer).
And undefined behaviour permits the compiler to do ANYTHING - it might even (appear to) work, only to suddenly stop working (or only work when you build in Debug mode, but not when in Release). So, for your own sake, please don't do that.

A: If you have a "thing" that holds an Object<T> where T is the Crtp-type, that "thing" is likely a template anyway.
So instead of holding an Object<T>, why don't you just hold a T, which is the full type that inherits from Object<T>. If that is destroyed it will call T::~T() automatically.
In addition, perhaps you want to do private or protected inheritance from Object<T> to discourage users from slicing the Crtp-type.

Edit: You can simplify your Ts by moving the actual work into Object<T>:
class VertexBuffer : public Object<VertexBuffer>
{
public:
    VertexBuffer() : Object<VertextBuffer>(glGenBuffers, glDeleteBuffers, 1) {
        ... // more stuff you did in your original constructor
    }
};

Where Object looks like this in addition to what you already have:
template <typename T>
class Object {
  void (*release)(int, std::uint32_t*);
  int i;

  Object() = delete;
  Object(void (*acquire)(int, std::uint32_t*), void (*release)(int, std::uint32_t*), int i = 1) : release{release}, i{i} {
    acquire(i, &m_Id);
  }
  ~Object() {
    release(i, &m_Id);
  }

  // rest of your Object class
};

A: This is close to the model of std::unique_ptr<> with a custom deleter. But it doesn't quite fit because std::unique_ptr has to hold a pointer and this case needs an integer handle-type.
So here is a brief example. It is general good advice to prefer inclusion over inheritance so I have deliberately placed the helper object inside the owning class.
All I'm really trying to demonstrate here is that there are a number of ways to customise behaviours in templates beyond call members of instances.
#include <iostream>
#include <memory>

typedef size_t gd_size;
typedef int gd_handle;

void gen_buffers(gd_size size,gd_handle*buffs);
void del_buffers(gd_size size,gd_handle*buffs);

typedef void (*gd_func)(gd_size,gd_handle*buff);

template<gd_func gfunc,gd_func dfunc> class GenDel{
    public:
        GenDel(){gfunc(1,&buff);}
        ~GenDel(){dfunc(1,&buff);}
        int get()const{return buff;}
    private:
    int buff;

    GenDel(const GenDel&)=delete;
};

class BufferHolder{
public:

   BufferHolder(){}

   void do_thing() const{
       std::cout<<"using "<<buffer.get()<<'\n';
   }

 private:
    GenDel<gen_buffers,del_buffers> buffer;
};

int main() {
    BufferHolder b;
    BufferHolder c;

    b.do_thing();

    return 0;
}

int seed{0};

void gen_buffers(gd_size size,gd_handle*buffs){
    for(size_t i{0};i<size;++i){
        buffs[i]=++seed;
        std::cout << "generated "<< buffs[i] << '\n';
    }
}

void del_buffers(gd_size size,gd_handle*buffs){
        for(gd_size i{0};i<size;++i){
        std::cout << "deleted "<< buffs[i] << '\n';
    }
}


text:
Q: Multithreading issue : I want add an extra thread to write and save that 4 threads that already read from 4 text files in a new text file I have 4 threads reading from 4 text files and print it on the screen. I want to make extra thread to write & save that 4 threads read in a new text file.
Current Code:
import pandas as pd
import threading
from datetime import datetime

start_time = datetime.now()

def print_text(filename):
    text = pd.read_csv(filename, delimiter = "\t")
    print(text)

if __name__ == "__main__":
    filenames = ['file1.txt', "file2.txt", "file3.txt", "file4.txt"]

    # Create thread for each filename.
    threads = [threading.Thread(target=print_text, args=(filename,)) for filename in filenames]

    # Start execution of each thread.
    for thread in threads:
        thread.start()

    # Join threads when execution is complete.
    for thread in threads:
        thread.join()

time_elapsed = datetime.now() - start_time

print('Time elapsed (hh:mm:ss.ms) {}'.format(time_elapsed))

A: This shows how to use a queue to route the output of your four "writer" threads to a "reader" thread.  The astute reader will realize that there is no point in spawning a 5th thread for this.  We could call print_result in the mainline code and get the same result with lower overhead.
import queue
import threading
from datetime import datetime

start_time = datetime.now()

def print_text(q, filename):
    for line in open(filename):
        q.put(line.strip())
    q.put('--end--')

def print_result(q, count=0):
    while count:
        line = q.get()
        if line == '--end--':
            count -= 1
        else:
            print(line)

if __name__ == "__main__":
    filenames = ['file1.txt', "file2.txt", "file3.txt", "file4.txt"]
    q = queue.Queue()
    threads = [threading.Thread(target=print_text, args=(q, filename)) for filename in filenames]
    threads.append( threading.Thread(target=print_result, args=(q, len(filenames))) )

    # Start execution of each thread.
    for thread in threads:
        thread.start()

    # Join threads when execution is complete.
    for thread in threads:
        thread.join()

time_elapsed = datetime.now() - start_time

print('Time elapsed (hh:mm:ss.ms) {}'.format(time_elapsed))


text:
Q: Block diagram function to duplicate y-axis in LabVIEW I am trying to make a dynamic XY-graph in LabVIEW, in which I'd like to be able to set a number of y-axis during execution. I have so far found only the "mouse-clicky" version of duplicating a y-axes, i.e. right-clicking it on the front panel etc.
Is there a way to do this during execution, via a property node or similar?

A: What i would do is to create the amount of Y axis i know a user could use. For example; if you know user could need two Y axis in the application, right click on the Y axis in the chart and duplicate it. This will create two axis in your application with indexes 0 and 1.
Then by using property nodes you can select the index of the active Y scale, and make it visible or invisible in runtime.

A: You cannot add and remove scales programmatically.
But you can hide/show existing scales.
So you should configure a preset list of scales, then show/hide them according to your needs.
Here is an code snippet. Drag and drop the picture in your block diagram in order to have the ready to use code.


text:
Q: How do you connect PyVisa to an Arduino Uno? I'm trying to connect my Arduino Uno to my computer and writing code in python using PyVisa. I have installed PyVisa correctly, since it has worked with other devices. For some reason the Arduino Uno never returns a response. I'm using the NI Visa package, because I was hoping the pyvisa-py was the problem. Is there something I'm missing?
The code I am using to connect is:
import pyvisa_py as pv

port = "ASRL4::INSTR"
rm = pv.ResourceManager()
device = rm.open_resource(port)

The ResourceManager finds the correct port, and I don't get an error making the device. When I try to use a query however, like
print(device.query("*IBN?"))

It gives the following error:
pyvisa.errors.VisaIOError: VI_ERROR_TMO (-1073807339): Timeout expired before operation completed.

A: I haven't tried to use an Arduino with PyVisa in a long time. I always use the PySerial library instead. Here is a personal note I wrote about four years ago (in 2017) for a Python module interfacing with an Arduino.

This driver does not use the VISA layer to communicate with the device. Instead, it uses the more low-level and less general PySerial library. The reason for that is that the Arduino reboots ("resets itself") whenever the serial port is opened through VISA. This is a feature, not a bug, so that you don't have to manually reset it every time you flash a new firmware version from the Arduino IDE. As a consequence, though, the controller will not respond to requests for about two seconds after opening its serial port. The only way to avoid the reboot is making sure that the serial port's DTR line is not toggled when opening the resource. VISA, however, does so by default, and there seems to be no way to disable this disruptive behavior. In fact, VISA attributes cannot be set until after the resource has been opened. The PySerial library, on the other hand, does not have this limitation.

As the note is four years old, take it with a grain of salt. Things may have changed. But using PySerial instead of PyVisa is still your best bet. See my answer here for a few more details. And maybe do a web search with the keywords "Arduino" and "DTR" to see if there have been any recent developments.


text:
Q: django. GenericForeginKey null when content_type and object_id is set I have the following fields
content_type=models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
posted_wall = generic.GenericForeignKey('content_type', 'object_id')

And I don't get why posted_wall is None below..
(Pdb) p thread.content_type
p thread.content_type
<ContentType: foo>
(Pdb) p thread.object_id
p thread.object_id
18
(Pdb) p thread.posted_wall
p thread.posted_wall
None
(Pdb)

I noticed you can't use genericForeginKey field when filtering on queryset.
Are there other cases where I shouldn't try to access GenericForeignKey field?
EDIT
The object access is done in dehydrate_something in tastypie.
I guess the bundle.obj is not fully populated in dehydrate_FOO .


text:
Q: Why does express routing go a level deep instead of top-level page path? When using this app.js file to route an express app,
var itemRouter = express.Router();

app.use('/items', itemRouter);

itemRouter.route('/').get(function (req, res) {
  res.render('items');
});

itemRouter.route('/single').get(function (req, res) {
  res.render('singleItem');
});

why does /single route to http://localhost:3000/items/single and not to http://localhost:3000/single? what is telling express to add to the page path instead of create a new one?

A: To be more specific, inside app.js you have assigned itemRouter to the base path "/item". There are benefits to this, since itemRouter can be kept in a separate file handling all the items sub-directories, but thats out of scope and it seems you've found your answer.

A: Because the middleware has app.use, the  route is being set to that path


text:
Q: Can Elastic Load Balancer scale automatically? I know it will sound weird but here is my question:
When I tested my app in Cloud9 it worked just fine. Then, right after I deployed my app in an ECS Fargate container behind the Application Load Balancer and went to my ALB DNS name I saw that my app was buggy (it seems like my TCP connection (socket.io) latency was very high and my ALB couldn't handle the load). It happened late in the evening.
Then, the next day when I went to my website it worked great! It seems like my ALB scaled up somehow and that is the reason why my app became normal.
Am I guessing right? Did my ALB indeed scale up? How can I monitor or read about this?

A: AWS load balancers will scale up/down depending on the traffic. It, however, can take a few minutes for AWS to adjust capacity to the demand. If you are expecting increase in traffic, you can contact AWS in advance to let them know that Load balancer would need scaling - obviously that makes sense only if you anticipate increase due to scheduled event/sale/etc and scaling on-demand is unacceptable.
AWS docs for reference:
AWS-LB-Details
Elastic Load Balancing scales your load balancer as traffic to your application changes over time.

*

*You could try to resolve the dns name with "nslookup" command to check what IP addresses are assigned. I believe there's no way o keep track of scaling activity, as it happens behind the scenes within AWS.

*Make use of Access logs, those can be stored on s3 for further analysis.
You can query for data to see how many requests were rejected, or whats the processing time. For the details and available metrics take a look at the docs:
AWS-access-logs


text:
Q: Edit a web page button with CSS I am new to HTML/CSS and I want to edit the style of a button.
This is the html code:

START EXPLORING

and this is the CSS:
.btn-sign-in {
  width: 180px;
  height: 50px;
  -webkit-border-radius: 5px;
  border-radius: 5px;
  background-color: #10cb6c;
  line-height: 50px;
  color: #fff;
  font-size: 16px;
  text-align: center;
  display: block;
  -webkit-transition: .4s;
  -o-transition: .4s;
  transition: .4s;
  white-space: nowrap
}

.btn-sign-in:hover {
  color: #fff;
  background-color: #2add82
}

What I want to achieve is this style https://codepen.io/Cyris/pen/abpjJrK.
Already tried to apply the CSS code to my .btn-sign-in from the link above but is not working at 100%.
What I am doing wrong?

A: Please use this
<button class="btn-sign-in">START EXPLORING</button>

A: You need to use the button component, not the link


text:
Q: HTTP through a proxy server is not allowed When I try to connect to my Tomcat server on http://<servername>:8080 it works fine, but from another ISP provided it gives the following error:
HTTP through a proxy server is not allowed.

Some ISP apparently don't allow http over the port 8080, as they think the client uses a proxy.
I also have a httpd running on port 80 for my website.
So in order to avoid the proxy error, I would like to make to following routing:

*

*If the user connects to http://<servername>, then the website is served via apache.

*If the user connects to  http://<servername>/AppName, then the port is rerouted to 8080, without the client (or his ISP) knowing.

Is that possible (using iptables or something else)  ?
Thank you

A: you can configure Apache to do this for you using mod_proxy
In your apache conf add something like this
ProxyPass /appName http://localhost:8080/appName
ProxyPassReverse /appName http://localhost:8080/appName

http://httpd.apache.org/docs/current/mod/mod_proxy.html
With Tomcat you can also use mod_proxy AJP
http://httpd.apache.org/docs/current/mod/mod_proxy_ajp.html


text:
Q: Firebase Auth Couldn't Verify Domain I have a Firebase account, and I want to tailor the email address from which verification emails are sent. I follow the instructions.

I have a domain registered with 1&1 and set up as instructed.

But after about 2 days, I get the following.

Please can anyone advise.  Thanks

A: I also was unable to verify my custom domain for the auth templates.
My solution was to remove my custom domain from the host name in the DNS records needed for the verification.
Example:

TXT record: from contoso.com to @
CNAME record: from firebase._domainkey.contoso.com to firebase._domainkey

Note: My domain is hosted by Godaddy.com

A: Maybe the trailing space on your TXT record?
$ dig txt thewhozoo.com

; <<>> DiG 9.8.3-P1 <<>> txt thewhozoo.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 59407
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;thewhozoo.com.         IN  TXT

;; ANSWER SECTION:
thewhozoo.com.      3600    IN  TXT "firebase=thewhozoo-143913 "
thewhozoo.com.      3600    IN  TXT "v=spf1 include:_spf.firebasemail.com ~all "

;; Query time: 45 msec
;; SERVER: 192.168.1.1#53(192.168.1.1)
;; WHEN: Thu Jun  8 23:49:07 2017
;; MSG SIZE  rcvd: 125

A: For those using Cloudflare. Make sure you don't have DNS flattening activated in the CNAME.


text:
Q: Server Error in '/' Application () I created a OData ADO.NET Framework web api which I am testing in localhost and am getting the error
Line 19:             if (!EventLog.SourceExists("MyService"))

The StackTrace is:
[SecurityException: The source was not found, but some or all event logs could not be searched.  Inaccessible logs: Security.]
   System.Diagnostics.EventLog.FindSourceRegistration(String source, String machineName, Boolean readOnly, Boolean wantToCreate) +657
   System.Diagnostics.EventLog.SourceExists(String source, String machineName, Boolean wantToCreate) +104
   System.Diagnostics.EventLog.SourceExists(String source) +14

How should I remove this error ? Thanks a lot.
My web.config has:
  <system.web>
    <authentication mode="Windows">
      <forms requireSSL="true" />
    </authentication>
    <authorization>
      <allow roles="MyService" />
      <deny users="*" />
    </authorization>

    <httpCookies requireSSL="true" httpOnlyCookies="true" />
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" enableVersionHeader="false"/>
  </system.web>

A: The process for removing bindings(Team Foundation Service - tfs) is simple:
Ensure you don't have the solution/projects open in Visual Studio
Copy your solution to a new directory (because the tool does modify files)
Run the utility from the command line: VSUnbindSourceControl.exe d:\mysolution folder
Once the tool is finished, all the source control bindings have been removed from any solution and project files.
Also have a look at this SO post


text:
Q: Proof of convergence of $\sum_{n=1}^{\infty}\frac{(-1)^{\lfloor n\sqrt{2}\rfloor}}{n}$ I had this task long long time ago in a calculus class. I remember it had a very elegant solution using nice property of $\text{Spec}(\sqrt{2})$,
where
$$
\text{Spec}(\alpha)=\{\lfloor\alpha n\rfloor\,:\,n=1,2,3,\ldots\}.
$$
I wasn't able to recreate the solution so I asked this question here.
Thanks to zwim I was able to recall the original solution. See my answer below.

A: Thanks to zwim I was able to recreate original solution which was beautiful. I just wanted recall that solution because it uses nice property from

Graham, Ronald L.; Knuth, Donald E.; Patashnik, Oren, Concrete mathematics: a foundation for computer science., Amsterdam: Addison-Wesley Publishing Group. xiii, 657 p. (1994). ZBL0836.00001, Section 3.2, Page 77.

Define a multiset of integers $\text{Spec}(\alpha)$:
$$
\text{Spec}(\alpha)=\{\lfloor\alpha n\rfloor\,:\,n=1,2,3,\ldots\}.
$$
Define a function $f(x)$ for positive real $x$:
$$
f(x)=\sum_{0<n<x}(-1)^{\lfloor n\sqrt{2}\rfloor}.
$$
There is a beautiful proof in "Concrete Mathematics" that $\text{Spec}(\sqrt{2})$ and $\text{Spec}(2+\sqrt{2})$ form a disjoint partition of the set of positive integers, thus
$$
\sum_{0<n\sqrt{2}<x}(-1)^{\lfloor n\sqrt{2}\rfloor}
+\sum_{0<n(2+\sqrt{2})<x}(-1)^{\lfloor n(2+\sqrt{2})\rfloor}
=
\sum_{0<n< \lceil x\rceil}(-1)^n\in\{-1,0\}.
$$
Since $(-1)^{\lfloor n(2+\sqrt{2})\rfloor}=(-1)^{\lfloor n\sqrt{2}\rfloor}$ we get
$$
f\left(\frac{x}{\sqrt{2}}\right)+f\left(\frac{x}{2+\sqrt{2}}\right)\in\{-1,0\},
$$
which leads to inequality:
$$
-1\le f((1+\sqrt{2})x)+f(x)\le 0
$$
for all positive real $x$.
Now, by induction over $k=0,1,2,\ldots$ one can prove such claim:
$$
0<x<(1+\sqrt{2})^k \implies |f(x)|\le k.
$$
As mentioned in https://artofproblemsolving.com/community/c7h39398p245740 (link provided by zwim)
using the Abel transform we conclude that our series converges if and only if the series $\sum_{n\geqslant 1}\frac {f(n+1)}{n(n+1)}$ converges and, in case of convergence, they converge to the same sum.
It is enough to show that $|f(x)|=O(\log x)$ - which we did.


text:
Q: some confusion about singleton set? Is the set  $\{0\}$ is closed in $(\mathbb{R} , |.|)$ ? where  $|.|$ denotes  the usual  metric on $\mathbb{R}$
My attempt :  yes , because  i think $\{0\}$  is not  open  for all  $x> 0, (x- \epsilon, x + \epsilon) \notin \{0\}$
Is its  correct?
Any hints/solution

A: "Not open" does not imply closed. What you need to show is that the complement $\mathbb{R} \setminus \{0\}$ is open, e.g. by writing $\mathbb{R} \setminus \{0\}$ as a union of open intervals.

A: No, it is not correct. Asserting that $\{0\}$ is closed in $\mathbb R$ means that $\mathbb{R}\setminus\{0\}$ is open in $\mathbb R$. That is what you should try to prove (and it is not hard). But the assertion "$\{0\}$ is not open for all $x>0$, $(x-\varepsilon,x+\varepsilon)\notin\{0\}$" makes no sense.

A: Take any sequence in $\{0\}$. Then it must be the zero sequence and thus converges to 0, which lies in the set. So $\{0\}$ is closed.


text:
Q: Adding DbContext for list of context types at runtime To implement a plug-in system in a AspNet Core Mvc app, I would like a non-generic method to add a data context from a list of assemblies loaded dynamically at runtime, taking a Type parameter like this:
    foreach(Type tp in pluginContexts)
    {
        services.AddDbContext(tp, options => ...);
    }

instead of the usual
    services.AddDbContext<PluginDataContext>(options => ...);

That's because for dynamically loaded assemblies, I can not provide the TContext type parameter to the AddDbContextPool method, since that's statically compiled and not available at compile time.
Background
This is for a larger Asp.Net Core MVC app. The plugins must be able to both access the main database of the overall app and a separate database of their own.
Plugin assemblies, containing domain code and their private database context are to be dropped in a specified directory.
The main app loads the plugin assembly dynamically upon startup.
The way I am solving this now is to have each controller get the IConfiguration instance injected, obtain the appropriate connection string from the config, and the database context is instantiated in the controller. Not so nice but does work.
One can easily inject a general class into the Services collection with AddScoped<>, and then use it as a sort of ServiceLocator - however, that is considered an antipattern.
I looked into the source code for AddDbContext but honestly I am lost.
Is there any simple way to achieve this?

A: Solved it by creating an extensibility point in the plugin assembly.
Define an interface in the main app, which all plugins must implement.
  public interface IPluginContextRegistration
  {
      void RegisterContext(ref IServiceCollection services, Action<DbContextOptionsBuilder> optionsAction);
      String GetDatabaseName();
  }

Create a class implementing this interface (in the plugin). It has access to the type of its private database context, thus can use the generic AddDbContext method:
   public class DatabaseRegistration : IPluginContextRegistration
   {
       public void RegisterContext(ref IServiceCollection services, Action<DbContextOptionsBuilder> optionsAction)
       {
           services.AddDbContext<Test1DbContext>(optionsAction);
       }

       public String GetDatabaseName()
       {
           return "test-plugin-db";
       }
   }

Then in the main app ASP.Net Startup.cs file, add following code, which calls the RegisterContext() method for each plugin. For example, if you want to use Sql Server:
    void RegisterPluginDbContexts(ref IServiceCollection services, List<Assembly> assemblyList)
    {
        IEnumerable<IPluginContextRegistration> registrars = new List<IPluginContextRegistration>();
        foreach (Assembly assembly in assemblyList)
        {
            registrars = registrars.Concat(GetClassInstances<IPluginContextRegistration>(assembly));
        }
        foreach (var reg in registrars)
        {
            String name = reg.GetDatabaseName();
            String connStr = Configuration.GetConnectionString(name);
            reg.RegisterContext(ref services, options => options.UseSqlServer(connStr));
        }
    }

For completeness - the method "GetClassInstances" is just a helper method using Reflection to obtain an instance of classes implementing the specified interface.
So it's simple after all - no need for re-writing framework code .


text:
Q: Easy data storage formats for c++ begginners I'm making a c++ program and need a way to store data for users and things like that. I've tried JSON, but the libraries are very difficult to use, at least for a beginner like me. I am looking for a key-value pair type format. JSON work, if I could find an easier library for that.

A: If you are looking for storage formats for data, then options are -

*

*XML (3rd party libraries available)

*JSON (3rd party libraries available)

*INI file (key value pair in text file)

*CSV format (text file)

*Object serialization
etc

Storage mechanisms are -

*

*File store (XML, JSON, CSV as plain text file)

*Database (RDBMS, Object store)

*In memory objects

Above are few regularly used storage techniques in C++ (and many other languages also).
~Nilesh


text:
Q: Retrieve SharedPreferences in retrofit2 interface I'm trying to add programmatically an authorization header to my api calls with retrofit and rxjava2 so i added an okhttp3 interceptor to it. This is my full code:
public interface APIService {

    class ServiceInterceptor implements Interceptor{

        @NonNull
        @Override
        public okhttp3.Response intercept(@NonNull Chain chain) throws IOException {
            Request request = chain.request();
            if (request.header("No-Authentication") == null){
                SharedPreferences sharedPref = ???.getSharedPreferences(USER, Context.MODE_PRIVATE); <---
                request = request.newBuilder()
                        .addHeader("Authorization", "JWT " + sharedPref.getString("auth_token", null))
                        .build();
            }
            return chain.proceed(request);
        }
    }

    OkHttpClient apiClient = new OkHttpClient().newBuilder()
            .addInterceptor(new ServiceInterceptor())
            .build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://192.168.1.8:8000/api/v1/")
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .client(apiClient)
            .build();

    @GET("rest-auth/user/")
    Single<Response<User>> getUserDetails();

    @POST("rest-auth/login/")
    @Headers("No-Authorization: true")
    Single<Response<AuthUserResponse>> loginUser(@Body LoginRequest body);

    @POST("rest-auth/registration/")
    @Headers("No-Authorization: true")
    Single<Response<AuthUserResponse>> signupUser(@Body SignupRequest body);

}

The problem is that i can't retrieve the auth_token from sharedPreferences because i don't know how to pass the context to it. Any suggestions?
Thanks.

A: You need to create a constructor for your ServiceInterceptor class, passing the auth_token as a param, something like
 private String authToken;

 public ServiceInterceptor(String authToken) {
     this.authToken = authToken;
 }

That way you handle the context and SharedPreferences outside your interceptor class, it shouldn't know about android stuff anyway.
Then on your intercept method you can get the authToken.


text:
Q: JavaScript to JQuery; formatting date for MySQL So after trial and error, I've finally got my calendar running the way I'd like. I have it only allowing a certain time slot to be selected. It's anywhere from 10 to 21 days from whatever the current date is. However, I'm plugging this new calendar into a slot where another calendar preexisted and I need to ensure that the values get passed into MySQL correctly, based off how it was previously set up.
The code that existed previously was JavaScript and I changed it over to JQuery. The previous code had this line in it:
dateFormat: 'yy-mm-dd' // MySQL datetime format

Now, I'd like the same date format for my new calendar if possible.

$(document).ready(function () {
   $('.txtDeadline').datepicker({ minDate: +10, maxDate: +21 });
  });

// Still needs dateFormat: 'yy-mm-dd' for MySQL datetime format

<link href="//code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />

 Deadline*

  <input class="txtDeadline" name="txtDeadline" type="text" />

Min: 10 days Max: 21 days from current date

A:

$(document).ready(function () {
   $('.txtDeadline').datepicker({ minDate: +10, maxDate: +21,dateFormat: 'yy-mm-dd' });
  });

// Still needs dateFormat: 'yy-mm-dd' for MySQL datetime format

<link href="//code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />

 Deadline*

  <input class="txtDeadline" name="txtDeadline" type="text" />

Min: 10 days Max: 21 days from current date


text:
Q: Passing multiple values to :not() jQuery? I want to filter multiple values from an event in jQuery.
At the moment I have:
.filter(":not(.element)")

How would I go about adding more things to filter? I've tried:
.filter(":not(.element, .another, .etc)")

and
.filter(":not(.element)").filter(":not(.another)").filter(":not(.etc)")

and
.filter(":not(.element),:not(.another),:not(.etc)")

With no luck. What do I need to do?
Thanks.
EDIT: Thanks for the answers - I've find another solution to my problem that avoids having to do what I've asked in the question, but evidently I wasn't doing something properly in my code since the solutions posted work. I will mark an answer as correct, many thanks.

A: It is working, you just need to separate each element using a comma (,) in the :not() selector.
You can check the example here:
http://jsfiddle.net/LVUMs/

A: Looks like it is working. http://jsbin.com/uyayot/edit#javascript,html
I tried:
$('div').not('#div2,#div4').each ( function () {
    alert ( $(this).attr ('id' ) );
  });

A: You can use not() by chaining it. Like this
$('yourElement').not(':even').not('.SomeMore').not('.fewmore')


text:
Q: Why do we use gerunds? I am very impress the way he explained the perfect infinitive. I tried to contact him but found no email. Could any one kind enough to explain the gerunds as he explained perfect infinitive?
Perfect infinitive
I'm new here. If I'm not following any rules please pardon me.

A: A gerund is a noun formed from a verb by adding the -ing ending to the bare infinitive.

Leaping uses the leg muscles.

Sometimes spelling conventions require the consonant to be doubled, but that's a historical orthographic artefact and it has got nothing to do with the grammatical function of the word:

Jogging is a form of exercise.

The gerund allows us to refer to the action of the verb nominally, so it can be used as a subject or object.
P.S. Not every word ending in -ing is a gerund. Some are participles, functioning as verbs, and some even function as gradable adjectives.
P.P.S. There are verbs, moreover, for which it would not be idiomatic to express the nominal with a gerund, for example, confuse, whose nominal form is confusion not confusing.

A: Terminology: Gerunds and infinitives are both verbals.
First, if a verb can take a verbal as an "object" or complement, it's going to be an infinitive and has nothing to do with the below.  Sometimes the to is omitted.

I want to walk away.
I want to say to him what I think.

The main function of the infinitive is to let you use a verb without predicating anything—that is, separately from making a claim.
For example, in "The cat wishes to sit on the mat", the verb is "wishes", and the sentence claims that the cat is wishing something.

@BenKovitz's answer from your referenced question is very good.
In this sentence:

The cat wishes to sit on the mat

"To sit" is being talked about abstractly here.  Whereas in something like this:

Falling asleep was not good for the cat, it got caught by an eagle

"Falling asleep" is not abstract.  It's referring to an actual instance of that action being performed.
If you switch to the infinitive, then you are talking about something that might/could/would/wants to happen, not something that was happening or did happen.

To fall asleep was not good for the cat, it would be in danger of getting caught by an eagle.  So the cat stayed awake.


text:
Q: How to have individual .idea folders on a shared project We have multiple developers working on a shared project through dropbox. Each time one of the developers saves a file, the other developers get the following message:
"Project Files Changed
Project components were changed externally and cannot be reloaded:
ToolWindowManager
Would you like to reload project?"
How can each person have their own settings in a shared project so this is not a problem?

A: You should use VCS (Version control systems) as for example git, and ignore the IDE configuration files (.gitignore), so you can avoid the conflicts with the configuration files