text:
Q: C++ array initialization is this form  of intializing an array to all 0s
char myarray[ARRAY_SIZE] = {0}   supported by all compilers? ,
if so, is there similar syntax to other types? for example
bool myBoolArray[ARRAY_SIZE] = {false}

A: Note that the '=' is optional in C++11 universal initialization syntax, and it is generally considered better style to write :
char myarray[ARRAY_SIZE] {0}

A: Yes, this form of initialization is supported by all C++ compilers. It is a part of C++ language. In fact, it is an idiom that came to C++ from C language. In C language = { 0 } is an idiomatic universal zero-initializer. This is also almost the case in C++.
Since this initalizer is universal, for bool array you don't really need a different "syntax". 0 works as an initializer for bool type as well, so
bool myBoolArray[ARRAY_SIZE] = { 0 };

is guaranteed to initialize the entire array with false. As well as
char* myPtrArray[ARRAY_SIZE] = { 0 };

in guaranteed to initialize the whole array with null-pointers of type char *.
If you believe it improves readability, you can certainly use
bool myBoolArray[ARRAY_SIZE] = { false };
char* myPtrArray[ARRAY_SIZE] = { nullptr };

but the point is that = { 0 } variant gives you exactly the same result.
However, in C++ = { 0 } might not work for all types, like enum types, for example, which cannot be initialized with integral 0. But C++ supports the shorter form
T myArray[ARRAY_SIZE] = {};

i.e. just an empty pair of {}. This will default-initialize an array of any type (assuming the elements allow default initialization), which means that for basic (scalar) types the entire array will be properly zero-initialized.

A: Yes, I believe it should work and it can also be applied to other data types.
For class arrays though, if there are fewer items in the initializer list than elements in the array, the default constructor is used for the remaining elements. If no default constructor is defined for the class, the initializer list must be complete — that is, there must be one initializer for each element in the array.

A: You can declare the array in C++ in these type of ways.
If you know the array size then you should declare the array for:
integer: int myArray[array_size];
Double: double myArray[array_size];
Char and string : char myStringArray[array_size];
The difference between char and string is as follows
char myCharArray[6]={'a','b','c','d','e','f'};
char myStringArray[6]="abcdef";

If you don't know the size of array then you should leave the array blank like following.
integer: int myArray[array_size];
Double: double myArray[array_size];

A: Additionally, keep a note of how the array and vector are default initialized if don't initialize them explicitly.
int main()
{
    bool arr1[3];                   // true  true  true  [here true is SOME garbage value]
    std::vector<bool> vec1(3);      // false false false

    bool arr2[3] = { true };        // true false false [here true/false are REAL true/false values]
    vector<bool> vec2(3, true);     // true true  true

    bool arr3[3] = { false };         // false false false
    std::vector<bool> vec3(3, false); // false false false

    int arr4[3];                      // GV GV GV - garbage value
    std::vector<int> vec4(3);         // 0 0 0

    int arr5[3] = { 1 };              // 1 0 0
    std::vector<int> vec5(3, 1);      // 1 1 1

    int arr6[3] = { 0 };              // 0 0 0
    std::vector<int> vec6(3, 0);      // 0 0 0
}


text:
Q: How do I create a query that takes two columns and filters by latest version each column A by the latest version number in column B? I have three tables.

*

*Holds different family names. Example: familyA, familyB, familyC, etc.

*Holds available versions. Example: A01, A02, A03, etc.

*List of filenames with foreign key reference to the other two tables. This has every combination that exists.  Example: familyA_A01, familyA_A02, familyB_A01, familyB_A02, familyB_A03 etc.
I need a query that will give me the latest A00 version from the third table.
Result would look like familyA_A02, familyB_A03.

A: You can do it with the operator LIKE:
select columnname
from tablename
where columnname like '%\_A0%' escape '\'

The underscore _ needs to be escaped because it is a wild char for the operator LIKE.
This query will return all values in the column columnname that conatain _A0

redpajama_set_name: RedPajamaStackExchange


text:
Q: Characterizing abstract Hilbert spaces Let me start with a theorem that we can prove :
If $H$ is a Hilbert space over $\mathbb{C}$ and $E$ is any set such that $|E|= dim(H)$, the dimension of $H$ being the cardinality of an orthonormal basis of $H$. Then $H$ is isomorphic to the Hilbert space
$$\ell_2(E, \mathbb{C})= \{f: E \to \mathbb{C}|\{\alpha \in E| f(\alpha)\neq 0 \} \text{ is countable and } \sum_{\alpha \in E}|f(\alpha)|^2<\infty \}$$
equipped with the inner product $\langle f, g\rangle= \sum_{\alpha\in E} f(\alpha)\overline{g(\alpha)} $
Can we have a similar fact but for general measure spaces? like $L_2(E, \mathbb{C})$ for example? if we drop the countability requirement?
How big can a Hilbert space be? I am assuming if $H$ is separable then its dimension must not exceed $c=2^{\aleph_o}$ .
If $H$ is not separable, can it have a dimension bigger than $c$ ? how about arbitrarily bigger ?
This questions is important for some problems in operator theory, we are given an abstract Hilbert space $H$ and we are asked to build operators on $H$, we have some nice results from operators on $L_2$ that we want to translate in $H$, so it would be always nice to write $H\cong L_2(E,\mathbb{C})$ for some $E$ .

A: Your example, $\ell^2(E)$, produces a Hilbert space with dimension $|E|$, so any cardinal can appear as the dimension of $H$.
$H$ is separable if and only if $\dim H\leq\aleph_0$. This is simple: if you have an uncountable orthonormal basis, this is an uncountable family of elements at fixed distance $\sqrt2$ of each other; so $H$ cannot be separable. And conversely, when $\dim H<\infty$ or $\dim H=\aleph_0$, it is easy to produce a countable dense subset.
Note that $\ell^2(E)=L^2(E)$ with the counting measure, so you can always do what you want. If you want a "meaty" measure space (say, diffuse), you can start with the separable space $L^2[0,1]$ and consider $L^2[0,1]^{|E|}$. I'm not sure how straightforward or not it is to consider the product measure on an infinite Cartesian product, though. I would say that for non-separable Hilbert spaces the advantages of looking at $L^2$ would be greatly reduced as you won't have the usual things that make $L^2[0,1]$ nice (polynomials, continuous functions, etc.).

A: Let $A$ be any non-empty set and $H$ be the space of all functions $f: A \to \mathbb R$ such that $\sum_{a \in A} |f(a)|^{2}<\infty$ where $\sum_{a \in A} |f(a)|^{2}$ is defined as the the supremum of all sums of the form $ \sum\limits_{k=1}^{n}|f(a_k)|^{2}$ where $\{a_1,a_2,...,a_n\}$ runs over all finite subsets of $A$. Define $ \langle f, g \rangle =\sum_{a \in A} f(a)g(a)$. This makes $H$  a Hilbert space and the  functions $\{f_a: a \in A\}$ form an orthonormal basis for $H$ where $f_a (b)=1$ if $a=b$ and $0$ otherwise. The Hilbert space dimension of this space is exactly the cardinality of $A$.


text:
Q: Algorithm for hamming or parity bit calculation? i'm trying to write a program to find hamming code in java ,but have a slight confusion regarding hamming code calculation ,
Below is what most tutorials say,
Example :For a n bit message, say 8 bit message we require k=4 parity or hamming bits placed in positions of powers of 2( numbered 1 to k+n from right to left ), see below example
8 bit message =11000100
k=4

hence
Bit position         12   11  10   9    8     7     6   5    4   3    2    1
                     d     d   d   d    P8    d     d   d   P4   d    P2   P1

where P1...P4 are the parity bits
Next ,to calculate the value of the parity bits the instruction tells me to blindly do this
Each parity bit is calculated as follows:

    P1 = XOR of bits (3, 5, 7, 9, 11)   =   1⊕1⊕0⊕0⊕0 = 0
    P2  =XOR of bits (3, 6, 7, 10, 11) =   1⊕0⊕0⊕1⊕0 = 0
    P4  =XOR of bits (5, 6, 7, 12)      =   1⊕0⊕0⊕0 = 1
    P8  =XOR of bits (9, 10, 11, 12)   =   0⊕1⊕0⊕0 = 1

Is there some method to do this , or should i just memorize this ?based on what do they arrive at XOR(3,5...etc).Some kind of an algorithm for it?
NOTE: To write a Java program to find hamming code for any n bit number i require an explanation to this, so i hope the question qualifies in Stack-overflow


text:
Q: Is there any algorithm with the time complexity of O(n*(log n)^2)? I know that heapsort has a time complexity of O(n log n), but I can't really think of an algorithm that has one of O(n (log n)2).

A: It is super easy to construct one. The most obvious example is:
for i in xrange(n * int(log(n, 2) ** 2)):
   // do something O(1)

For a more helpful example you can use Master's theorem to come up with infinite amount of recursions that satisfy your needs (any k will work):

If you are looking for a real algorithm, then Shellsort has a worst case complexity of O(n (log n)2). The same for an inplace mergesort.
P.S. a fancy name for the stuff you are looking for is quasilinear time complexity with k = 2.

A: A classic (and most practical) example is stable_sort of STL. The log-quadratic factor comes due to the merge stage itself being recursive (which allows the entire algorithm to run in-place).

A: https://en.wikipedia.org/wiki/Dynamization tends to increase complexity by a factor of log n, so the if you do n queries of the dynamized version of a data structure with underlying cost log n, you will get n log(n)^2


text:
Q: Correct unit testing I started using unit and functionality test with this project and because of this I have some questions:
Im working with the symfony php framework. And I have a doctrine like LDAP ORM service.
Furthermore I have a user repository (as a service) which depends on the LDAP ORM service, the logger and a validation service.
Now I want to write a unit test for the addUser function of the UserRepo.
It will internally call: getNewUidNumber, userToEntities, doesUserExist and getUserByUid.
My question is:
Should I mock all these internal function to just test the addUser function? Would that be against the unit test idea (just test the API).
Or should I just mock the LDAP ORM service, the Logger, and the validation  service, so that the class calls all internal functions? But this would cause a huge test function with a lot of mocking because I have to mock the repositories for all internal repositories calls.
Or should I start the symfony kernel and use the ServiceContainer to use the ORM LDAP service with a real test database. But wouldn't that be a functionally test and not a unit test?
I heard that its bad to have so many dependencies in a test. So I thought it would be bad to use the whole serviceContainer.
Adduser:
public function addUser(User $user)
{
    $pbnlAccount = $this->userToEntities($user);

    if(!$this->doesUserExist($user)) {
        $pbnlAccount->setUidNumber($this->getNewUidNumber());
        $this->ldapEntityManager->persist($pbnlAccount);
        $this->ldapEntityManager->flush();
    }
    else {
        throw new UserAlreadyExistException("The user ".$user->getUid()." already exists.");
    }

    return $this->getUserByUid($user->getUid());
}

For more code, like the internal functions:
https://gist.github.com/NKPmedia/4a6ee55b6bb96e8af409debd98950678
Thanks
Paul

A: First, I would like to rewrite the method a tiny bit, if I may.
public function addUser(User $user)
{
    if ($this->doesUserExist($user)) {
        throw new UserAlreadyExistException("The user ".$user->getUid()." already exists.");
    }

    // ... shortened for brevity
    $pbnlAccount = $this->userToEntities($user);
    $this->ldapEntityManager->persist($pbnlAccount);
}

The other relevant method is:
private function doesUserExist(User $user)
{
    $users = $this->ldapRepository->findByUid($user->getUid());
    return count($users) === 1;
}

Immediately we can see that we basically have two tests:

*

*We test that the method throws when the user exists

*We test that the method persists a PbnlAccount if the user does not exist.

If you do not see why we have these two tests, note that there are 2 possible "flows" in this method: one where the block inside the if statement is executed, and one where it is not executed.
Lets tackle the first one:
public function testAddUserThrowsWhenUserExistsAlready()
{
    $user = new User();
    $user->setUid('123');

    $ldapRepositoryMock = $this->createMock(LdapRepository::class);
    $ldapRepositoryMock
        ->method('findByUid')
        ->expects($this->once())
        ->with('123')
        ->willReturn(new PbnlAccount());

    $userRepository = new UserRepository($ldapRepositoryMock);

    $this->expectException(UserAlreadyExistException::class);
    $userRepository->addUser($user);
}

The second test is left as an exercise for the reader :)
Yes you will have to do some mocking in your case. You wil need to mock the LdapRepository and LdapEntityManager both in this case.
Note 1: this code probably is not runnable, since I do not know the exact details of your code base (and I wrote this off the top of my head), but that is beside the point. The point is that you want to test for the exception.
Note 2:
I would rename your function to createNewPbnlAccountForUser(User $user) which is longer, but more descriptive of what it actually does.
Note 3:
I am not sure why you are returning $this->getUserByUid() since that seems redundant (you already have the User right there), so I am ommitting that case.

A: You need to mock ldapEntityManager and all repository services but not the internal function.And as you said, don't boot kernel in unit test. So, you should test all cases with success and throwing exception (make sure to check all behaviour)

A: If you want to perform a unit test, you should mock all collaborators.
Now, entity managers, ldap services and so on should not be mocked (read more here).
Moreover, if you happen to be in a situation where the Arrange part (set mocks, stubs, and  so on) is painful and take "a lot" of the test, maybe this is a smell that your class has too many responsibility (is doing too much things).
That said, when I do unit test, I would like the test to fail only for an internal (to the class) reason, not because I've changed a collaborator line that messes up all my tests.


text:
Q: How to specify certain labels on matplotlib legend I try to produce the following plot, but the legend doesn't look very good. I want years to be integer number (not decimals) and space in periods like 2000, 2005, 2010, 2015, 2020 in the colorbar. Also legend title "Years" should be on top of the legend (not in the middle color bar) with fontsize=14. Hope someone can help.
import pandas as pd
import random
import matplotlib.pyplot as plt
df=pd.read_csv(r"https://raw.githubusercontent.com/tuyenhavan/Course_Data/main/data.csv")
years=[i for i in range(2000,2022)]
df["Year"]=[random.choice(years) for i in range(len(df))]
fig, ax=plt.subplots(figsize=(15,8))
point=plt.scatter(df.Extent_km2/1000, df.Resolution_m, c=df.Year)
plt.xticks(fontsize=13)
plt.yticks(fontsize=13)
ax.set_xlabel(r"Spatial extent (1000 $\rmkm^2$)", fontsize=15)
ax.set_ylabel("Spatial resolution (m)", fontsize=15)
fig.colorbar(point)
plt.show()

A: To change your colorbar ticks, you can set customized ticks with cb=plt.colorbar(points,ticks=np.arange(2000,2025,5)). To place, the title of your colorbar at the top, you can use: cb.ax.set_title('Years',fontsize=14).
Overall, the code looks like that:
import pandas as pd
import random
import matplotlib.pyplot as plt
import numpy as np

df=pd.read_csv(r"https://raw.githubusercontent.com/tuyenhavan/Course_Data/main/data.csv")
years=[i for i in range(2000,2022)]

df["Year"]=[random.choice(years) for i in range(len(df))]
fig, ax=plt.subplots(figsize=(15,8))
points=ax.scatter(df.Extent_km2/1000, df.Resolution_m, c=df.Year)

ax.tick_params(axis='both', which='major', labelsize=13)
ax.set_xlabel(r"Spatial extent (1000 $\rmkm^2$)", fontsize=15)
ax.set_ylabel("Spatial resolution (m)", fontsize=15)

#setting up colorbar with customized ticks
cb=plt.colorbar(points,ticks=np.arange(2000,2025,5))

#setting up title
cb.ax.set_title('Years',fontsize=14)
plt.show()

And the output gives:


text:
Q: npm dev run generates huge main.js file I have a Django application and trying to rewrite my JS frontend to React. I found some tutorial how to organize the structure of React app:
frontend/

*

*static/frontend/main.js/main.js

src/

*

*index.js

*components/App.js

package.json
    {
  "name": "frontend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ],
  "scripts": {
    "dev": "webpack --mode development ./src/index.js --output-path ./static/frontend/main.js",
    "build": "webpack --mode production ./src/index.js --output-path ./static/frontend/main.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.20.12",
    "@babel/preset-env": "^7.20.2",
    "@babel/preset-react": "^7.18.6",
    "babel-loader": "^9.1.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "webpack": "^5.75.0",
    "webpack-cli": "^5.0.1"
  },
  "dependencies": {
    "fs-promise": "^2.0.3"
  }
}

webpack.config.js
module.exports = {
  devtool: false,
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: { presets: ['@babel/env','@babel/preset-react'] },
        }
      }
    ]
  }
};

index.html
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Django REST with React</title>

Anything

{% load static %}

sample code in App.js
import React from 'react';
import ReactDOM from 'react-dom';

 function App() {
       const [value, setValue] = React.useState(0);

       function increment() {
         setValue(value + 1);
       }

       return (

{value}

           <button onClick={increment}>+1</button>

       );
     }

     ReactDOM.render(

         <App />

,
       document.getElementById("root")
     );

const container = document.getElementById("app");
ReactDOM.render(<App />, container);

If I got it right, any React component imported in index.js will be compiled to js code in main.js which is included to index.html. I created a simple code in App.js just to try it and it does work, but it generates a 30k lines main.js file. Is it normal? I guess it shouldn't be like this since it consumes much more resources than my 400-lines js code, so what am I doing wrong ?part of code in main.js


text:
Q: Thymeleaf - Displaying a button after every two items in a list brand new to thymeleaf. Below I have a table that in one column displays all the names (strings) in a list, and in the other column if the iterator is even then it displays a button.

                    test
                    test

But all of the buttons are appearing outside of the table, above it.
Why is this happening?

A: This happened because of the line 'th:remove="tag"' This works:

                    test
                    test


text:
Q: Best way to test apps against test environments Not sure if this is the right forum and struggling to articulate this questions but here goes:
We have a process in place where we regularly release testflight app builds in order to test new functionality and fixes in our app. We always point these builds at our production environment (API's, databases, etc). This causes us some issues like:

*

*We are regularly trying to test stuff which has not yet been released to production (i.e. backend stuff may have not been updated yet)

*When we do move code from our backend test environment to our production environment it has potentially not been tested as the app never points there.

*We dont see what our real production users see as we are always on more advanced builds.

I am sure there are a number of ways we could do this a lot better but a key requirement we have going forward is to be able to release versions of our app which point to our test environment so we can correctly test things end-to-end to help alleviate the above issues. At the same time we also need versions of our app pointing at production as we use the app ourselves day to day.
The two obvious choices that I can come up with are:
Option 1 - Have separate test and production apps
By this I mean we have two apps released with two separate bundle id's and names (like app_test and app_prod). You can then load both of these apps on your phone at the same time.
Option 2 - Same app built to either point at test or prod
This is basically where I would release the same app pointing at either production or test. You can only have one or the other on your phone at any one time.
Option 1 feels like the right thing to do but I have a number of issues with it:

*

*The configuration of push and provisioning certificates will be more complicated

*Inbound push notifications will be hard to understand and debug on phones if you have the two apps running

*We would need to either submit a second app to app stores or we will need to use a third party release tool like hockeyapp or whatever.

*Our semi automated build process would need reworking to support multiple bundle ids and stuff
Option 2 on the other hand presents itself with problems too:

*

*You can only have test or production apps on a single device at any one time. This implies we would need to get more devices to test from

*There is a risk of releasing an app pointing to test environments to our production users.
I guess a 3rd option would be to have the ability to reconfigure the app to use either environment (by way of a hidden dev menu or something). This concerns us in regards to caching settings but maybe that could be worked around. I guess it also means we could only run one version of the app on a device at any one time.
Anyway, this is quite an open question for advice. I am really keen to hear what other people are doing when it comes to testing apps. I have read up a bit on this and spoken to a number of people to get input (which is what leads me to the above two options) but would appreciate more input and advice. How do you solve this problem? Maybe I am just approaching this from the completely wrong angle!


text:
Q: Can I specify the path to biblatex annotation files The biblatex package allows you to write annotations to your bibliography as external files. I use those annotations to keep notes associated to the papers I read for my thesis.
Unfortunately, since the annotation of each bibliography entry has to be in a separate file, my TeX source directory gets quite cluttered. It would therefore be preferable if all annotations were in a separate directory but I cannot find a way to tell biblatex where to look for them. So my question is the following:
Is there any way to tell biblatex to look for the annotation files in a directory different from the current one?

A: Joe's right, try putting your files in a common directory and use relative path from where your .tex document is.


text:
Q: php json_decode returns NULL with syntax error At the risk of duplication, here is my very own struggle with json_decode(). I've been through many if not all the posts on this and nothing has worked. So here goes:
Here is a sample of my json variable's content:
{"id":"212","game":"36","player":"1","currentChallenge":"3","startDate":"1456575719","endDate":"1456575918","attempts":"0","completed":"1"}

I checked it on http://jsonlint.com/ and it's good
I am running these filters as per other forum suggestions:
$response = utf8_encode($response);
$response = str_replace('"', '"', $response);

And here is my decode line:
var_dump(json_decode($response, true));

I still get a NULL response and a syntax error (json_last_error()).
This data is coming from my own database and api. I tried inputting manually to the database and querying that, figuring I could get rid of any problems created by the input process. No luck there. And I have also sampled various tables to be sure it is not a problem related to the database setup.
And here is all my code:
if (isset($_POST['submit']) ) {

    $table = $_POST['table'];
    $id = $_POST['id'];
    $url = 'http://example.com/api.php/' . $table . '/' . $id;

    $client = curl_init($url);
    curl_setopt($client,CURLOPT_RETURNTRANSFER,true);

    $response = curl_exec($client);
    if ($response === false) {
        $info = curl_getinfo($curl);
        curl_close($curl);
        die('error occured during curl exec. Additioanl info: ' . var_export($info));
    }

    $response = utf8_encode($response);
    $response = str_replace('"', '"', $response);
    echo $response;

    echo '<br />Result of json_decode: ';
    var_dump(json_decode($response, true));

    $json_errors = array(
        JSON_ERROR_NONE => 'No error has occurred',
        JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
        JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
        JSON_ERROR_SYNTAX => 'Syntax error',
    );
    echo 'Last error : ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL;

}

Thank you!


text:
Q: notifyChange with changed uri from contentProvider.update() i have implemented update() of ContentProvider and notifying to observer using getContext().getContentResolver().notifyChange(uri, null);
my obvious need is that whenever just one row is effected i want to notify with row specific uri, but could not find way to do so.
an additional query like "select id where selectionArgs" can do this but this will be a foolish way.
onchange(boolean, uri) get complete uri instead of specific row, easy to understand that this is because ContentProvider.update() is sending the same.
some code for more clarity

update()  method of MyContentProvider
 @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {

        Log.d("TAG", "update " + uri.getPath());

        int count = 0;
        switch (uriMatcher.match(uri)) {
        case BOOKS:
            count = booksDB.update(DATABASE_TABLE, values, selection, selectionArgs);
            break;
        case BOOK_ID:
            count = booksDB.update(DATABASE_TABLE, values,
                    _ID + " = " + uri.getPathSegments().get(1)
                            + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""),
                    selectionArgs);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        if (count == 1) {
            Cursor c = query(uri, new String[] { _ID }, selection, selectionArgs, null);
            long rowId = Long.valueOf(c.getString(c.getColumnIndex(_ID)));
            uri = ContentUris.withAppendedId(CONTENT_URI, rowId);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;

    }

i will update table some how like
getContentResolver().update(MyContentProvider.CONTENT_URI, values1, MyContentProvider._ID+"<?", new String[]{"3"}));

frankly saying, code has barely related to question, just trying to give you some context

A: In your provider method, just return the uri with the id appended
@Override
public Uri insert(Uri uri, ContentValues values) {
    Log.i(TAG, "insert " + uri);
    final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    final int match = URI_MATCHER.match(uri);

    Uri returnUri;
    switch (match) {
        case MESSAGE: {
            long _id = db.insert(MessageContract.MessageEntry.TABLE_NAME, null, values);
            if (_id > 0)
                returnUri = ContentUris.withAppendedId(MessageContract.MessageEntry.CONTENT_URI, _id);
            else
                throw new android.database.SQLException("Failed to insert row into " + uri);
            break;
        }

        default:
            throw new UnsupportedOperationException("Unknown uri: " + uri);
    }

    getContext().getContentResolver().notifyChange(returnUri, null);

    return returnUri;
}

And register your observer with true for descendents.
getContentResolver().registerContentObserver(MessageContract.MessageEntry.CONTENT_URI, true, mContentObserver);

To get the id from a Uri you can use ContentUris.parseId(uri)

A: Unfortunately I'm not able to suggest easy solution (because I'm not aware of full code and updates You need to run), there's some ways we You could try (some of them I've implemented in mine applications):

*

*Provide ids in ContentValues - this way looks not applicable for Your case and it needs loop with calls to notifyChange();

*Provide specific Uri for requests with queries (only some specific apps needs many various queries in selection, usually it's much easier to include query parameter in Uri). After another part of the program get notification with that specific Uri it will be able to check if it's 'current item' was updated and act appropriately (e.g. simplest case with list of articles and one article open in separate activity; then You update list of articles in the background from server You might need to update currently open article also and so, need to know if it was updated). You should be able to check particular item on the side of the observer using just received Uri, because it (Uri) will contain parameter(s) You've used for query;

A: You can pass the ID via ContentValues, and append it to the notification url. This way you don't have to make a separate query.
@Override
public int update(@NonNull Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    int rows = _database.update(getTableName(), values, selection, selectionArgs);
    if (rows > 0) {
        Uri itemUri = ContentUris.withAppendedId(uri, values.getAsLong(DatabaseModel.COLUMN_ID)); // DatabaseModel.COLUMN_ID is "_id"

        getContext().getContentResolver().notifyChange(itemUri, null);
    }
    return rows;
}


text:
Q: how can i subtract the data from sql table How can i subtract two columns based on  AccountGroupId 4 -  AccountGroupId 5
I have data like :

ID      Month     Year    AccountGroupName    AccountGroupId   Balance

1       February  2014    Expense                5             200
2       February  2014    Income                 4             300
3       March     2014    Expense                5             250
4       March     2014    Income                 4             200

Desired Result :

ID      Month     Year    AccountGroupName    AccountGroupId   Balance

1       February  2014    Income                 4             100
2       March     2014    Expense                5            -50

Query :
IF OBJECT_ID('tempdb..#temptbale') IS NOT NULL DROP TABLE #temptbale
IF OBJECT_ID('tempdb..#subTable') IS NOT NULL DROP TABLE #subTable

    SELECT
    (DATENAME(Month,JD.CreatedDateTime)) as [Month],
    DATEPART(yyyy ,JD.CreatedDateTime) as [Year],
    AG.AccountGroupName,
    AT.AccountGroupID,
    Sum(A.OpeningBalance)  as Balance
    into #temptbale
    FROM AccountGroup AG
    INNER JOIN AccountType AT ON AG.AccountGroupID=AT.AccountGroupID
    Right join Account A on A.AccountTypeID = AT.AccountTypeID
    Inner join JournalMasterDetail JD on JD.AccountID = A.AccountID
     where AG.AccountGroupID > 3 and year(JD.CreatedDateTime) = year(getdate())
            and datepart(dy, JD.CreatedDateTime) <= datepart(dy, getdate())
    group by
    A.AccountName,
    JD.CreatedDateTime,
    AG.AccountGroupName,
    A.OpeningBalance,
    AT.AccountGroupID

    select ROW_NUMBER() OVER(ORDER BY [Month]) AS 'ID',[Month],[Year],AccountGroupName,AccountGroupID,SUM(Balance)as Balance
    into #subTable
     from #temptbale
    group by

    [Month],
    AccountGroupName,
    AccountGroupID,
    [Year]
    order by
    [Month]

    select * from #subTable

A: You can run this query
select t.Month,t.Year
,Case when tblExp.Balance > tblIncome.Balance then tblExp.AccountGroupName else tblIncome.AccountGroupName end as AccountGroupName
,Case when tblExp.Balance > tblIncome.Balance then tblExp. AccountGroupId else tblIncome. AccountGroupId end as AccountGroupId
,tblIncome.Balance - tblExp.Balance as Balance
from table t
inner join(select * from table where AccountGroupId = 4) as tblExp on tblExp.year = t.year and tblexp.Month = t.Month
inner join(select * from table where AccountGroupId = 5) as tblIncome on tblIncome.year = t.year and tblIncome.Month = t.Month
group by t.Month,t.Year

It's joining the Month and year with two derived tables as Income and expense


text:
Q: heading problem H1 in CSS I'm not able to change the size and color of heading h1 in my site.
I have used an external Css file.
code as below..
h1 {
    Background-color : red;
    Color : green;
}

A: An URL would be helpful.
Also, CSS rules are lowercase. (e.g. background-color, not Background-color)
Read about CSS specifity, that is probably the problem: http://htmldog.com/guides/cssadvanced/specificity/

A: Try using Firebug or IE8 Developer Tools to inspect the element and make sure you don't have conflicting styles from another stylesheet or somewhere else in your html document.

A: Thats looks ok to me.
You may have an issue with the H1 already being set somewhere else in the style sheet.
Either you can search for it or make your adjustments as important ie.
h1{
  background-color: #ff0000 !important;
  color: #00FF00 !important;
}

Hope this helps

A: Try setting '!important' behind it:
color: green !important;

Note that this only applies if there are other styles overriding your external css. You should test that your external CSS-file is read at all. You can do that by making a new paragraph for example. Give it an id (id="foo") and set this in your css
color: green;

If it doesn't turn green you should check your css include path.

A: You might also consider using the hex codes for the colors instead of "red" and "green" - I've seen that produce some odd behaviors in some browsers (or be ignored entirely).

A: h1 {
    background: red !important;
    color: green !important;
}

Also, depending on how your original h1 declaration was written, you can use specificity and cascading to overwrite the previous value(s).

A: Also, consider the ordering that you call your external stylesheets, you may have a your main css file appear first, and then a second stylesheet after that, which also has styles set on your H1, this may be overriding your first stylesheet - something to look into anyways.

A: I'm sure you've verified that the external stylesheet is loaded to your site and you are referencing it properly.

A: One way you will get this problem is if your css files is in subfolder say styles or styles\pages and you are not providing the full relative path.
say if the site.css file is in styles folder.
This will not load the style (because the path is provided and file is not in root)
<link rel="stylesheet" type="text/css" href="site.css" media="screen" />

This will load it correctly.
<link rel="stylesheet" type="text/css" href="styles/site.css" media="screen" />


text:
Q: How to align a Rails routes file with tabular? I want to align this snippet from a Rails routes file from this:
Rails.application.routes.draw do
  get 'about' => 'static_pages#about'
  get 'help' => 'static_pages#help'
  get 'contact' => 'static_pages#contact'
  get 'signup' => 'users#new'
  get 'login' => 'sessions#new'
  post 'login' => 'sessions#create'
  delete 'logout' => 'sessions#destroy'
end

To this:
Rails.application.routes.draw do
  get    'about'   => 'static_pages#about'
  get    'help'    => 'static_pages#help'
  get    'contact' => 'static_pages#contact'
  get    'signup'  => 'users#new'
  get    'login'   => 'sessions#new'
  post   'login'   => 'sessions#create'
  delete 'logout'  => 'sessions#destroy'
end

By using the tabular plugin for vim.
I've been trying all kinds of regexes but can't seem to nail it.
:Tabularize/'[^=]*\|=.*/l1l0 just mangles the texts.
The closest resource I can find is this question:
Tabular.vim : how to align on the first occurrence of 2 different delimiters placed at the beginning of Words?

A: Use the following:
:Tabularize/'[^']*'\|=>/l1l0

The idea is to use the strings and the hash rocket as delimiters.
I recommend you read all of :h tabular.
Although I have not tired vim-easy-align, I have heard that it makes some alignments easier than Tabular. It might be worth checking out.

A: I don't remember how you'd do it with Tabular but:
:%!column -t|sed 's/  \([^ ]\)/ \1/g'

or:
:%!column -t<CR>
:%s/  \([^ ]\)/ \1/g<CR>


text:
Q: Error messege "The source contains no DataRows" when i sent a data table object to a pagenation Class method I have a User Control with a DataGrid.Every thing was fine since the DataGride Pagenation Function within the User Control Class.I Desided to move the pagenation functions into a class instead.This is my Code
    {

    private static DataTable _dt ;
    private static TextBlock _PageInformation;
    private static ComboBox _NumberOfRecords;
    private static Button _btnPrev;
    private static Button _BtnFirst;
    private static Button _BtnNext;
    private static Button _BtnLast;
    internal static AssetsManagement equipmentManage
    {
        get { return equipmentMng; }
        set { equipmentMng = value; }
    }
    private static DataGrid _datagridObject;

    public static TextBlock PageInformation { get => _PageInformation; set => _PageInformation = value; }
    public static DataTable dt { get => _dt; set => _dt = value; }
    public static ComboBox NumberOfRecords { get => _NumberOfRecords; set => _NumberOfRecords = value; }
    public static DataGrid DatagridObject { get => _datagridObject; set => _datagridObject = value; }
    public static Button BtnPrev { get => _btnPrev; set => _btnPrev = value; }
    public static Button BtnFirst { get => _BtnFirst; set => _BtnFirst = value; }
    public static Button BtnNext { get => _BtnNext; set => _BtnNext = value; }
    public static Button BtnLast { get => _BtnLast; set => _BtnLast = value; }

    int pageIndex = 1;
    public static int numberOfRecPerPage;
    //To check the paging direction according to use selection.
    private enum PagingMode
    { First = 1, Next = 2, Previous = 3, Last = 4, PageCountChange = 5 };

    public Pagenation(DataGrid UCDatagrid,ComboBox NumberOfRecordsComboBox,TextBlock PageInfo,DataTable Data,Button Prev, Button First, Button Next, Button Last)
    {
        DatagridObject = UCDatagrid;

        dt = Data.Copy();
        if (Data == null)
        {
            MessageBox.Show(Data.Rows.Count.ToString());
        }
        PageInformation = PageInfo;
        NumberOfRecords = NumberOfRecordsComboBox;

        Prev = BtnPrev;
        First = BtnFirst;
        Next= BtnNext;
       Last= BtnLast;
        NumberOfRecordsComboBox.Items.Add("5");
        NumberOfRecordsComboBox.Items.Add("10");
        NumberOfRecordsComboBox.Items.Add("15");
        NumberOfRecordsComboBox.Items.Add("20");
        NumberOfRecordsComboBox.Items.Add("25");
        RefreshDataGrid(dt);
    }
    public  void BtnFirst_Click(object sender, RoutedEventArgs e)
    {
        Navigate((int)PagingMode.First);

    }
    public void BtnNext_Click()
    {
        Navigate((int)PagingMode.Next);

    }

    public void BtnPrev_Click(object sender, RoutedEventArgs e)
    {
        Navigate((int)PagingMode.Previous);

    }

    public void BtnLast_Click(object sender, RoutedEventArgs e)
    {
        Navigate((int)PagingMode.Last);

    }
    public void CbNumberOfRecords_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        Navigate((int)PagingMode.PageCountChange);
    }

    private void Navigate(int mode)
    {
        int count;
        switch (mode)
        {
            case (int)PagingMode.Next:
                BtnPrev.IsEnabled = true;
                BtnFirst.IsEnabled = true;
                if (dt.Rows.Count >= (pageIndex * numberOfRecPerPage))
                {
                    if (dt.AsEnumerable().Skip(pageIndex *
                    numberOfRecPerPage).Take(numberOfRecPerPage).Count() == 0)
                    {
                        DatagridObject.ItemsSource = null;
                        DatagridObject.ItemsSource = dt.Rows.Count <= 0 ? null : dt.AsEnumerable().Skip((pageIndex *
                        numberOfRecPerPage) - numberOfRecPerPage).Take(numberOfRecPerPage).CopyToDataTable().DefaultView;
                        count = (pageIndex * numberOfRecPerPage) +
                        (dt.AsEnumerable().Skip(pageIndex *
                        numberOfRecPerPage).Take(numberOfRecPerPage)).Count();
                    }
                    else
                    {
                        DatagridObject.ItemsSource = null;
                        DatagridObject.ItemsSource = dt.Rows.Count <= 0 ? null : dt.AsEnumerable().Skip(pageIndex *
                        numberOfRecPerPage).Take(numberOfRecPerPage).CopyToDataTable().DefaultView;
                        count = (pageIndex * numberOfRecPerPage) +
                        (dt.AsEnumerable().Skip(pageIndex * numberOfRecPerPage).Take(numberOfRecPerPage)).Count();
                        pageIndex++;
                    }

                    PageInformation.Text = count + " of " + dt.Rows.Count;
                }

                else
                {
                    BtnNext.IsEnabled = false;
                    BtnLast.IsEnabled = false;
                }

                break;
            case (int)PagingMode.Previous:
                BtnNext.IsEnabled = true;
                BtnLast.IsEnabled = true;
                if (pageIndex > 1)
                {
                    pageIndex -= 1;
                    DatagridObject.ItemsSource = null;
                    if (pageIndex == 1)
                    {
                        DatagridObject.ItemsSource = dt.Rows.Count <= 0 ? null : dt.AsEnumerable().Take(numberOfRecPerPage).CopyToDataTable().DefaultView;
                        count = dt.AsEnumerable().Take(numberOfRecPerPage).Count();
                        PageInformation.Text = count + " of " + dt.Rows.Count;
                    }
                    else
                    {
                        DatagridObject.ItemsSource = dt.Rows.Count <= 0 ? null : dt.AsEnumerable().Skip
                        (pageIndex * numberOfRecPerPage).Take(numberOfRecPerPage).CopyToDataTable().DefaultView;
                        count = Math.Min(pageIndex * numberOfRecPerPage, dt.Rows.Count);
                        PageInformation.Text = count + " of " + dt.Rows.Count;

                    }
                }
                else
                {
                    BtnPrev.IsEnabled = false;
                    BtnFirst.IsEnabled = false;
                }
                break;

            case (int)PagingMode.First:
                pageIndex = 2;
                Navigate((int)PagingMode.Previous);
                break;
            case (int)PagingMode.Last:
                pageIndex = (dt.Rows.Count / numberOfRecPerPage);
                Navigate((int)PagingMode.Next);
                break;

            case (int)PagingMode.PageCountChange:
                numberOfRecPerPage = Convert.ToInt32(NumberOfRecords.SelectedItem);
                DatagridObject.ItemsSource = null;
                DatagridObject.ItemsSource = dt.Rows.Count <= 0 ? null : dt.AsEnumerable().Take(numberOfRecPerPage).CopyToDataTable().DefaultView;
                count = (dt.AsEnumerable().Take(numberOfRecPerPage)).Count();
                PageInformation.Text = count + " of " + dt.Rows.Count;
                BtnNext.IsEnabled = true;
                BtnLast.IsEnabled = true;
                BtnPrev.IsEnabled = true;
                BtnFirst.IsEnabled = true;
                break;
        }
    }
    public static void RefreshDataGrid(DataTable dte)
    {
        MessageBox.Show(dte.Rows.Count.ToString());

        dt = dte.Copy();
        MessageBox.Show(dt.Rows.Count.ToString());

        DatagridObject.ItemsSource = null;
        DatagridObject.ItemsSource = dt.AsEnumerable().Take(numberOfRecPerPage).CopyToDataTable().DefaultView;

        int count = dt.AsEnumerable().Take(numberOfRecPerPage).Count();
        PageInformation.Text = count + " of " + dt.Rows.Count;

    }

}}

and in the Class of the UserControl I instantaite an object of the Pagenation Class with the constructor that takes all the needed varaible for pagenation.
 public PartsUC()
    {
        InitializeComponent();
        PartsDataTable = PartMng.GetAllEquipments();
        MessageBox.Show(PartsDataTable.Rows.Count.ToString());
        PageInformation = lblpageInformation;
         Partsdatagrid = this.PartsDataGrid;
        CbNumberOfRecords = this.cbNumberOfRecords;//the interface XAMAL Combobox

       Pagenation pagenation = new Pagenation(Partsdatagrid, cbNumberOfRecords, PageInformation, PartsDataTable, btnPrev, btnFirst, btnNext, btnLast);
        //Pagenation.RefreshDataGrid(PartsDataTable);}

The problem is that i still getting this error message!

The source contains no DataRows
  and the error points to the refreshDataGrid method in this line

DatagridObject.ItemsSource = dt.AsEnumerable().Take(numberOfRecPerPage).CopyToDataTable().DefaultView;

Note that the messege box in the function refreshDataGrid shows that i have 50 rows.

A: Solved it,The thing that caused the error was the function Take() since it takes the number from the combobox that let you choose how many rows to display.I put Fixed number and It Worked.
DatagridObject.ItemsSource = dt.AsEnumerable().Take(15).CopyToDataTable().DefaultView;


text:
Q: Can I get Performance Monitor to stop a Data Collector Set when a process exits? I am currently debugging a program crash and need data on its memory usage over time. This crash often happens after an extended amount of time open, especially overnight.
To this end, I have defined a Performance Monitor Data Collector Set to log the process' memory usage. However, due to the long running-time, I do not want to leave the counters active indefinitely. And due to the unknown end-time I am unable to use any of the duration stop conditions:

How can I stop the collection when the process ends?

A: While there doesn't seem to be an option within Performance Monitor itself, the command-line interface (logman) opens the possibility for a scripted solution.
PowerShell has the command Wait-Process, which blocks until the specified process ends.
Combining those, we get the solution, in PowerShell:
Wait-Process programname; sleep 30; logman stop datacollectorsetname

The sleep is there to allow time for the collector to log one or two entries after the process ends.


text:
Q: Why can't I change permissions for share So, I have a external Hard drive that I am trying to share on my network. It is plugged into the usb on my TVpc, and I want to be able to access and change folders and files from my laptop. When I go to change permissions with the GUI, I click the drop down and click to change permissions, but even if I click read and write under guests or other, it will automatically change back to "None."  I have no idea how to fix this and I cant access my files from another computer. any help?!

A: "It is plugged into the usb on my TVpc"
The access permissions are set by whatever is "sharing" out your disk filesystem on that machine.
You cannot change permissions on your remote disk filesystem from another computer unless the TVPc gives you permission to do so.
Please be security-wise and do not just make the permissions on your disk world writeable (or perhaps even world readable if there is sensitive material on the disk) to anybody who can access the local network.
If the PcTV is sharing using CIFS/SMB protocol, you could apply settings in the smb.conf file to require authentication with a password to some generic account eg "nobody"   On your other PC you can easily setup autofs to automagically mount the exported CIFS share with the user/password combination in a secure root only readable file.
The same is also possible with NFS exports and autofs mouting of them.
The threat now is not just via the local ethernet/wireless network but also now via signals received by the TV itself.
It has been discovered that it is possible via the broadcast Hibb TV protocol (this is a service transmitted over the air and via satellite) to get access to TVs and to perhaps even open devices on the local network.
http://www.itnews.com.au/News/345632,hbbtv-holes-make-tellys-hackable.aspx


text:
Q: How to avoid main script to be executed in / pages using react? I have a problem.
I'm using react for my website. And what i want to do is to have completely different page after / (e.g.  www.test.com/FirstPage www.test.com/SecondPage) like a portfolio and i want them to have its own nav body and footer with its own js files and etc. But i face some issues
Now i have my main website like www.test.com and i am creating different one in www.test.com/differentone , and all css classes(if they have the same name as in main website) and javascript executes too. How do i avoid that, i want it to be completely different without inheriting any css or js for / websites. Does routing even allows pages to be independent ?
Cause even javascript file from main page tries to fire when i am in /SecondPage but it doesn't find content that's in main web page and it crashes.
Naming for every other file can be completely different but it does the same. I hope i explained it clearly enough to understand
I have my folder now like this

A: You can handle this with react-router. Here below is a small example code.
  <Router history={browserHistory}>
    <Route path='/dashboard' component={App} onEnter={requireAuth} >
      <IndexRoute component={MainContent} onEnter={requireAuth} />
      <Route path='/notes' component={Notelist} onEnter={requireAuth}></Route>
    </Route>
    <Route path='/invite/*' component={Invite}></Route>
    <Route path='/' component={Login}> </Route>
    <Route path='/changepassword/*' component={ChangePassword}></Route>
  </Router>

This is how you can handle your components with different css wrapping inside Route tags. Here Login component has different css whereas App component is the main dashboard page with different css.
You can keep all your css files in styles folder and call it in main.js something like this.
 import './styles/main.scss';


text:
Q: Calling a function every 10 minutes I'm not an expert, just a beginner. So I kindly ask that you write some code for me.
If I have two classes, CLASS A and CLASS B, and inside CLASS B there is a function called funb(). I want to call this function from CLASS A every ten minutes.
You have already given me some ideas, however I didn't quite understand.
Can you post some example code, please?

A: public class datetime {

    public String CurrentDate() {

        java.util.Date dt = new java.util.Date();
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = sdf.format(dt);
        return currentTime;

    }

    public static void main(String[] args) {
        class SayHello extends TimerTask {

            datetime thisObj = new datetime();

            public void run() {
                String todaysdate = thisObj.CurrentDate();
                System.out.println(todaysdate);
            }
        }
        Timer timer = new Timer();
        timer.schedule(new SayHello(), 0, 5000);
    }
}

A: Solution with Java 8
ClassB b = new ClassB();
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
Runnable task = () -> {
    b.funb();
};
executor.scheduleWithFixedDelay(task, 0, 10, TimeUnit.MINUTES);

A: Have a look at the ScheduledExecutorService:
Here is a class with a method that sets up a ScheduledExecutorService to beep every ten seconds for an hour:
 import static java.util.concurrent.TimeUnit.*;
 class BeeperControl {
    private final ScheduledExecutorService scheduler =
       Executors.newScheduledThreadPool(1);

    public void beepForAnHour() {
        final Runnable beeper = new Runnable() {
                public void run() { System.out.println("beep"); }
            };
        final ScheduledFuture<?> beeperHandle =
            scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
        scheduler.schedule(new Runnable() {
                public void run() { beeperHandle.cancel(true); }
            }, 60 * 60, SECONDS);
    }
 }

A: import java.util.Date;

import java.util.Timer;

import java.util.TimerTask;

public class ClassExecutingTask {

    long delay = 10 * 1000; // delay in milliseconds
    LoopTask task = new LoopTask();
    Timer timer = new Timer("TaskName");

    public void start() {
        timer.cancel();
        timer = new Timer("TaskName");
        Date executionDate = new Date(); // no params = now
        timer.scheduleAtFixedRate(task, executionDate, delay);
    }

    private class LoopTask extends TimerTask {
        public void run() {
            System.out.println("This message will print every 10 seconds.");
        }
    }

    public static void main(String[] args) {
        ClassExecutingTask executingTask = new ClassExecutingTask();
        executingTask.start();
    }

}

A: Try this. It will repeat the run() function every set minutes. To change the set minutes, change the MINUTES variable
int MINUTES = 10; // The delay in minutes
Timer timer = new Timer();
 timer.schedule(new TimerTask() {
    @Override
    public void run() { // Function runs every MINUTES minutes.
        // Run the code you want here
        CLASSB.funcb(); // If the function you wanted was static
    }
 }, 0, 1000 * 60 * MINUTES);
    // 1000 milliseconds in a second * 60 per minute * the MINUTES variable.

Don't forget to do the imports!
import java.util.Timer;
import java.util.TimerTask;

For more info, go here:

http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html
http://docs.oracle.com/javase/7/docs/api/java/util/TimerTask.html


text:
Q: Change status on promise status I was trying to change the button text on the promise status using custom directive.
so here is the code of my custom directive
.directive('myDir',function(){
          return {
            scope: {
              myDir: '&',
              afterValue: '@',
              beforeValue:'@',
              ngDisable:'=',
            },
            link: function ($scope, element, attrs) {
              element[0].innerHTML=$scope.beforeValue;
              element.bind('click',function(){
                console.log(element);

                element[0].innerHTML=$scope.afterValue;
                element[0].className+="disabled";
                element[0].disabled='true'
                $scope.myDir();
                //success i would like to change the status here
              })
            }
          }

        })

and my controller
.controller('myCtrl',[function(){
          var vm = this;
          console.log("MYCTRL");
          vm.fun= function(){
            //promise running here
          }
        }])

and here is plnkr link :
https://plnkr.co/edit/Qj9GG2?p=templates/
I am unable to read success of promise  in directive.

A: You can use .then to get the result of a promise. In the example below I create a promise which will be resolved after 2 seconds. When it's resolved the directive will change the text on the button.
I create a promise with $q, but it's the same thing if you do an ajax-call:
  vm.fun= function(){
    //promise running here
    return $http.get('www.foo.org');
  }

angular
        .module('myApp',[])
        .directive('myDir',function(){
          return {
            scope: {
              myDir: '&',
              afterValue: '@',
              beforeValue:'@',
              ngDisable:'=',
            },
            link: function ($scope, element, attrs) {
              element[0].innerHTML=$scope.beforeValue;
              element.bind('click',function(){
                element[0].innerHTML=$scope.afterValue;
                element[0].className+="disabled";
                element[0].disabled='true'
                $scope.myDir().then(function(){
                  //success i would like to change the status here
                  // Change status here...
                  console.log('Callback from promise. Everything is fine.');

                  element[0].disabled=false;
                  element[0].innerHTML = $scope.beforeValue;
                }, function(){
                    // Something went bad.
                    console.log('Callback from promise. Something went wrong.');
                });

              })
            }
          }

        })
        .controller('myCtrl',['$q', function($q){
          var vm = this;
          console.log("MYCTRL");
          vm.fun= function(){
            console.log('method called');
            // Create a promise here...
            var def = $q.defer();

            setTimeout(function(){
              console.log('done in controller');
              def.resolve();

              // You can also use reject if something went wrong.
              // def.reject();
            }, 2000)

            return def.promise;
          }
        }])

    <link data-require="bootstrap@3.3.7" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

  <button class="btn btn-primary" my-dir="$ctrl.fun()" after-value="Clicked" before-value="click" ng-disabled>Click</button>

Update based on comments:

When user clicks on button it should change text and disable the
  button and call invoke promise. the button text change and disable i
  am doing it in directive and invoking the promise in controller.

This is what's happening in the line $scope.myDir(), altough you don't invoke a promise. You call a function, which in turn returns a promise. How do you mean that the promise should be invoked?

next i want to depending of promise success or fail which is running
  on controller i would like to change the text and make disable false.

This is what's happening under .then(). If myDir() was successful. Then the code will change the status back on the button. This is done in the directive, since it's only the directive that knows about the button. You have both a success and error callback from the promise.


text:
Q: Detecting html textarea's change I'd like to monitor my textarea's changes with jQuery. I can do this with the keyup event and it works perfectly. But what event I can get when a user click on the textarea (right mouse click), then choose paste?
Click event occur only when the user click with the left mouse button on the textarea.
How can I handle this situation?

A: you can detect Pastes or Cuts into the textarea by:
$("#TextBox1").bind('paste', function(e) {
            alert('pasting text!');
        });
$("#TextBox1").bind('cut', function(e) {
            alert('cut text!');
        });

Or combine:
$("#Text1").bind('cut paste', function(e) {
    alert(e.type + ' text!');
});


text:
Q: New column to flag as top X based on another column for multiple products over a time series in python Question is long winded so I'll explain.
I have a dataframe which looks like this in python:
Date        Product        Score       Score_pct
01/01/2021  A              15          0.015
02/01/2021  A              18          0.025
01/01/2021  B              5           0.05
02/01/2021  B              9           0.04
01/01/2021  C              8           0.10
02/01/2021  C              19          0.055

I have data going back 5 years for each of my products (6 products) and my dataframe is ordered in the fashion as shown above. There is one entry per product per date as above.
I would like a new column to flag if the 'Score_pct' is in the top 10 over the history for that product. If it is then I would like it to return the corresponding value in the 'Score' column.
Lets say for product A the first two are in the top 10 and the last value for C is also in the top 10. The desired result would be this. Note that the ranking is within that product group.
Date        Product        Score       Score_pct      Flag
01/01/2021  A              15          0.015          15
02/01/2021  A              18          0.025          18
01/01/2021  B              5           0.05           NaN
02/01/2021  B              9           0.04           NaN
01/01/2021  C              8           0.10           NaN
02/01/2021  C              19          0.055          19

Many thanks in advance.

A: I believe the following is what you need.
(1) Let's create a longer example:
import pandas as pd

df = pd.DataFrame({"Date": ["01/01/2021", "02/01/2021", "03/01/2021", "04/01/2021", "01/01/2021", "02/01/2021", "03/01/2021", "04/01/2021", "01/01/2021", "02/01/2021", "03/01/2021", "04/01/2021"],
                   "Product":["A", "A", "A", "A", "B", "B", "B", "B", "C", "C", "C", "C"],
                   "Score":[15, 18, 12, 10, 5, 9, 7, 3, 8, 19, 3, 9],
                   "Score_pct": [0.015, 0.025, 0.02, 0.3, 0.05, 0.04, 0.02, 0.3, 0.10, 0.45, 0.02, 0.3]})

This gives us the DataFrame below.
Date    Product Score   Score_pct
0   01/01/2021  A   15  0.015
1   02/01/2021  A   18  0.025
2   03/01/2021  A   12  0.020
3   04/01/2021  A   10  0.300
4   01/01/2021  B   5   0.050
5   02/01/2021  B   9   0.040
6   03/01/2021  B   7   0.020
7   04/01/2021  B   3   0.300
8   01/01/2021  C   8   0.100
9   02/01/2021  C   19  0.450
10  03/01/2021  C   3   0.020
11  04/01/2021  C   9   0.300

(2) Then we can create a ranking for the products. Here I made a top 2 ranking, but in your case you have to define top = 10:
top = 2

ranking = df.groupby(['Product'])[['Score_pct']].apply(lambda x: x.nlargest(top, columns=['Score_pct'])).reset_index()[['Product','Score_pct']].sort_values(by=['Product','Score_pct'], ascending=[True, False])

In my top = 2 example the result is
Product Score_pct
0   A   0.300
1   A   0.025
2   B   0.300
3   B   0.050
4   C   0.450
5   C   0.300

(3) Bring the ranking into our original DataFrame:
df = df.merge(ranking, how="left", on=['Product', 'Score_pct'], indicator=True)

Leading us to
Date    Product Score   Score_pct   _merge
0   01/01/2021  A   15  0.015   left_only
1   02/01/2021  A   18  0.025   both
2   03/01/2021  A   12  0.020   left_only
3   04/01/2021  A   10  0.300   both
4   01/01/2021  B   5   0.050   both
5   02/01/2021  B   9   0.040   left_only
6   03/01/2021  B   7   0.020   left_only
7   04/01/2021  B   3   0.300   both
8   01/01/2021  C   8   0.100   left_only
9   02/01/2021  C   19  0.450   both
10  03/01/2021  C   3   0.020   left_only
11  04/01/2021  C   9   0.300   both

(4) Lastly, create the 'Flag' column with NaNs and then add the respective scores:
import numpy as np

df['Flag'] = np.NaN

df.loc[df['_merge']=="both", ['Flag']] = df[df['_merge']=="both"]['Score']

df.drop(['_merge'], axis=1, inplace=True) # optional

We end up with the following DataFrame:
Date    Product Score   Score_pct   Flag
0   01/01/2021  A   15  0.015   NaN
1   02/01/2021  A   18  0.025   18.0
2   03/01/2021  A   12  0.020   NaN
3   04/01/2021  A   10  0.300   10.0
4   01/01/2021  B   5   0.050   5.0
5   02/01/2021  B   9   0.040   NaN
6   03/01/2021  B   7   0.020   NaN
7   04/01/2021  B   3   0.300   3.0
8   01/01/2021  C   8   0.100   NaN
9   02/01/2021  C   19  0.450   19.0
10  03/01/2021  C   3   0.020   NaN
11  04/01/2021  C   9   0.300   9.0


text:
Q: Calling derived class's methods from pointer to base class via reinterpret_casting the method pointer. Is this UB? With a pointer to an object of a derived type assigned to a pointer of its base class, I've found that you can reinterpet_cast a method from the derived class to a pointer of the base class, even if the base class doesn't have any such function (virtual, hidden, or otherwise). And it can be dereferenced and called from there and it "just works". But I'd like to make sure it's not UB. Is this UB? Is it portable?
Compilable Example:
#include <cstdio>

struct A { /* no foo method */ };
struct B : public A { void foo(void){printf("foo");} };

typedef void (B::*B_FOO_PTR)( void );
typedef void (A::*A_FOO_PTR)( void );

int main ( void ) {
    B b;
    A* a = &b;

    // address of a and b are identical

    B_FOO_PTR b_ptr = &B::foo;
    // (a->*b_ptr)(); // COMPILE ERROR: calling B method from A. Not Allowed, but...

    A_FOO_PTR a_ptr = reinterpret_cast<A_FOO_PTR>(b_ptr);
    (a->*a_ptr)(); // works, outputs "foo"

    return 0;
}

A: This is undefined behaviour. The only pointer-to-member function conversions where you can call the result are:

*

*round-trip conversion, and

*pointer-to-member-of-base to pointer-to-member-of-derived.

You attempt the inverse of the second point, which is excluded from this list.


text:
Q: TeamCity Configuration Can't Restore From TeamCity NuGet Feed I'm setting up some CI with build configurations that require some NuGet packages. These NuGet packages are built on the same server which is nice. I've read that I can use TeamCity's NuGet feed to meet my requirements. I've been following this guide.
I've created the feed on the Build project which has generated the v1, v2, and v3 endpoints. For indexing packages, I've gone for the first option, namely

To index packages published by the selected build configurations only, add the NuGet packages indexer build feature to these build configurations.

as it seemed to be the most straight forward. The NuGet packages indexer feature is applied to the two configurations that build NuGet package artifacts. These artifacts are building correctly as seen below:

If I plug the v3 endpoing into Visual Studio Package Sources for example, I just get an authentication prompt followed by the error Unable to load the service index for source .../v3/index.json. Response status code does not indicate success: 401 (). If I paste the v3 endpoint into a browser, I get a json object with a collection of objects with properties @id, @type, and comment. v1 and v2 in the browser show me an XML file with an empty Packages collection.
How do I confirm my packages actually ended up in the feed and/or am I misunderstanding how the endpoints are used?
Update: Turns out it was indeed a misunderstanding on my part. The /v3/index.json lists actions one can take on the feed. Using /v3/query lists all packages hosted by the feed.
The remaining problem is the error trying to consume packages from the feed. TeamCity throws the following errors:
C:\Program Files\dotnet\sdk\3.1.201\NuGet.targets(124,5): error : Unable to load the service index for source <host>/httpAuth/app/nuget/feed/<project>/<feed_name>/v3/index.json
C:\Program Files\dotnet\sdk\3.1.201\NuGet.targets(124,5): error :   Response status code does not indicate success: 401 ().

Alongside the solution file in my vault is the following NuGet.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
     <add key="nugetserver" value="<host>/httpAuth/app/nuget/feed/<project>/<feed_name>/v3/index.json" />
  </packageSources>
</configuration>

Is something else required to connect all the dots?

A: Turns out TeamCity has a neat little feature where it can pretty easily reference a TeamCity feed within the NuGet Installer runner type as a build step by placing the feed into the Packages sources input. By executing this build step before the one that publishes my files, all is well.


text:
Q: InstallShield: new Basic MSI major upgrade from older InstallScript MSI leaves old ARP entry I am working on a new Basic MSI install in IS 2015 Professional, it is a major upgrade of a product that was previously installed with an installscript MSI (that I think was made in 2012).
The version, product, and package code are different and they share an upgrade code.
The old install gave the option to install for all users or just the current user, the new install is currently set to be 'all users' only.
When testing in virtualbox (having installed the old version for 'all users'), the old install uninstalls, and the new version installs successfully, but a broken entry remain in Add/Remove Programs for the old version. A new entry for the new version is of course also present.
The frustrating part is I am sure I had this working at one point (initially I had problems because I had not setup an upgrade path), but I do not know what I might have changed to to cause this error.
Any ideas how I can fix this or where to look next?

A: This is a known (but undocuemnted) bug in InstallShield 2012.
If you do a major or minor upgrade of an MSI project written with IS 2012, it leaves the old InstallShield_{} key under HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall.
This makes Windows display the old entry in Add/Remove Programs.
I don't know of a good way to solve it, what i did is to write an InstallScript function that I call at the end of each upgrade; see below. The parameter is the product name as appears in ARP. The function removes all keys with this display name, except the one which just installed, of course!
function FixMajorUpgradeBug(szDisplayName)
    STRING szFunctionName,szBaseKey,svString,svValue;
    LIST listResults;
    NUMBER nResult;
begin
    szBaseKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
    // go over the key, and remove all InstallShield_{} keys which have the given display name, except for the version installed by this very setup
    RegDBSetDefaultRoot(HKEY_LOCAL_MACHINE);
    listResults = ListCreate(STRINGLIST);
    nResult = RegDBQueryKey(szBaseKey,REGDB_KEYS,listResults);
    if nResult = 0 then
        nResult = ListGetFirstString (listResults, svString);
        while (nResult != END_OF_LIST)
            if (svString % "InstallShield_{") then
                if !(svString % PRODUCT_GUID) then
                    // delete only keys with the specified product name!
                    svValue = "";
                    GU_RegistryGetValue(szBaseKey + "\\" + svString,"DisplayName",svValue);
                    if (svValue = szDisplayName) then
                        RegDBSetDefaultRoot(HKEY_LOCAL_MACHINE);
                        RegDBDeleteKey(szBaseKey + "\\" + svString);
                    endif;
                endif;
            endif;
            nResult = ListGetNextString (listResults, svString);
        endwhile;
    endif;
    ListDestroy(listResults);
end;

Note - if your product is one of those which changes the display name after each upgrade (e.g. includes the version number in the name), you will need to do a somewhat smarter comparison than svValue = szDisplayName.

A: I ended up with 2 CA's one for 32 bit and one for 64 bit.
The 64-bit:
"[SystemFolder]cmd.exe" /C "echo y | reg delete HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\InstallShield_[ISACTIONPROP1]"
As a commit execution CA with execute condition: VersionNT64 AND IS_MAJOR_UPGRADE
Where "ISACTIONPROP1" is defined in an upgrade path (as the "Detect Property") to hold the previous product code.
The CA's execute in the Install Exec (after "WriteRegistryValues" and Admin Exec sequence (after "ScheduleReboot").
The 32-bit CA is almost identical except the condition has "NOT VersionNT64" and the registry path is different (basically w/o the Wow6432 in the path to the key).


text:
Q: Convergence of $(\sin x)^x$ This showed up on a forum and had no clear answer so I'm asking this here to see if anyone can give some light.
Define the sequence $$a_n := (\sin n)^n \ \forall n \in \mathbb{N}$$
How do you proof the existence of $\lim_{n\to \infty} a_n$?
Thanks.

A: My answer: It does not converge to anything! It must be clear that this does not converge to any non-zero $L$. So the question is: "Does it converge to zero."
Let the proposition $P$, be the "converges to zero!" statement. Then
$$P^c="\exists\varepsilon>0 \textrm{ s.t. } \#\{n\in\mathbb{N}\Big||\sin n|>\varepsilon^\frac{1}{n}\}=\infty"$$
But using the approximation
$\varepsilon^\frac{1}{n}\approx\frac{-\log\varepsilon}{n}$ This becomes
$$P^c="\exists a<\infty \textrm{ s.t. } \#\{n\in\mathbb{N}\Big||\sin n|>1-\frac{a}{n}\}=\infty"$$
Then it is easy to use the properties of the sine function to see that
$$P^c=Q_-\cup Q_+$$
With
$$Q_\pm="\#\Big\{n\in\mathbb{N}\Big||\{\frac{n}{2\pi}\mp\frac{1}{4}\}|<\frac{a}{\sqrt n}\Big\}=\infty"$$
From now on we focus only on the proposition $Q_+$ and try to prove it. Let $A$ be the conjecture
$A$: For any sequence $0\leq e_n\leq 1$ with infinite sum $\sum_0^\infty e_n$, any irrational number $\alpha\in(0,1)$ and any sequence $t_n\in[0, 1]$ for which the limit $\lim_{n\rightarrow\infty}t_n$ exists, the following holds
$$\#\Big\{(n, \{n\alpha\})\Big|n\in\mathbb{N}, |\{n\alpha\}-t_n|\leq e_n\Big\}=\infty$$
Then with $e_n=\min(1, \frac{a}{\sqrt n})$, $\alpha=\frac{1}{2\pi}$, $t_n=.25$ we get
$$A\Rightarrow Q_+\Rightarrow P^c$$
And
I believe $A$ holds. But to solve the recent problem it is easier to use Dirichlet's Approximation Theorem. It states that that for every irrational $\alpha\in(0,1)$ there is an infinite sequence $n_k$ for which $\{n_k\alpha\}\leq\frac{1}{n_k}$. Now consider the infinite sequence
$$m_k:=n_k\Big\lfloor\frac{1}{4\{n_k\alpha\}}\Big\rfloor$$
For this we have
$$m_k\{n_k\alpha\}^2=n_k\{n_k\alpha\}^2\Big\lfloor\frac{1}{4\{n_k\alpha\}}\Big\rfloor\leq.25n_k\{n_k\alpha\}\leq.25$$
Or equivalently
$$\{n_k\alpha\}\leq\frac{.5}{\sqrt{m_k}}$$
This guarantees
$$|\{m_k\alpha\}-.25|\leq\{n_k\alpha\}\leq\frac{.5}{\sqrt{m_k}}$$
Which proves $Q_+$.

A: This is a long comment, not a full answer!
Note that:
$$(\sin n)^n=\left(-i\sinh(-in)\right)^n=\frac{(-i)^n}{2^n}\left(e^{-in}-e^{in}\right)^n.$$
By the binomial expansion, we get:
$$\begin{align*}
s_n=(e^{-in}-e^{in})^n=\sum_{k=0}^n\binom{n}{k}e^{-ikn}(-1)^{n-k}e^{i(n-k)n}=\sum_{k=0}^n\binom{n}{k}(-1)^{n-k}e^{in(n-2k)}.
\end{align*}$$
Consider the following cases:

*

*If $n$ is even, then, we have:
$$s_n=\sum_{k=0}^{n/2}\binom{n}{k}(-1)^{k}e^{in(n-2k)}+\sum_{k=n/2+1}^n\binom{n}{k}(-1)^{k}e^{in(n-2k)}.$$
Let $l=n-k$ in the second sum:
$$\sum_{k=n/2+1}^n\binom{n}{k}(-1)^{k}e^{in(n-2k)}=\sum_{l=0}^{n/2-1}\binom{n}{n-l}(-1)^{n-l}e^{in(2l-n)}=\sum_{l=0}^{n/2-1}\binom{n}{l}(-1)^{l}e^{in(2l-n)}.$$
So, we get:
$$\begin{align*}s_n&=\sum_{k=0}^{n/2}\binom{n}{k}(-1)^{k}e^{in(n-2k)}+\sum_{l=0}^{n/2-1}\binom{n}{l}(-1)^{l}e^{in(2l-n)}=\\
&=\sum_{k=0}^{n/2}\binom{n}{k}(-1)^{k}e^{in(n-2k)}+\sum_{l=0}^{n/2}\binom{n}{l}(-1)^{l}e^{in(2l-n)}-\binom{n}{n/2}(-1)^{n/2}=\\
&=\sum_{k=0}^{n/2}\binom{n}{k}(-1)^{k}\left(e^{in(n-2k)}+e^{in(2k-n)}\right)-\binom{n}{n/2}(-1)^{n/2}=\\
&=2\sum_{k=0}^{n/2}\binom{n}{k}(-1)^{k}\frac{e^{in(n-2k)}+e^{-in(n-2k)}}{2}-\binom{n}{n/2}(-1)^{n/2}=\\
&=2\sum_{k=0}^{n/2}\binom{n}{k}(-1)^{k}\cosh(in(n-2k))-\binom{n}{n/2}(-1)^{n/2}=\\
&=2\sum_{k=0}^{n/2}\binom{n}{k}(-1)^{k}\cos(n(n-2k))-\binom{n}{n/2}(-1)^{n/2}.
\end{align*}$$

*If $n$ is odd, then, we have:
$$s_n=\sum_{k=0}^{(n-1)/2}\binom{n}{k}(-1)^{k}e^{in(n-2k)}+\sum_{k=(n+1)/2}^n\binom{n}{k}(-1)^{k}e^{in(n-2k)}.$$
Let $l=n-k$ in the second sum:
$$\sum_{k=n/2+1}^n\binom{n}{k}(-1)^{k}e^{in(n-2k)}=\sum_{l=0}^{(n-1)/2}\binom{n}{n-l}(-1)^{n-l}e^{in(2l-n)}=\sum_{l=0}^{(n-1)/2}\binom{n}{l}(-1)^{l}e^{in(2l-n)}.$$
So, we get:
$$\begin{align*}s_n&=\sum_{k=0}^{(n-1)/2}\binom{n}{k}(-1)^{k}e^{in(n-2k)}+\sum_{l=0}^{(n-1)/2}\binom{n}{l}(-1)^{l}e^{in(2l-n)}=\\
&=\sum_{k=0}^{(n-1)/2}\binom{n}{k}(-1)^{k}\left(e^{in(n-2k)}+e^{in(2k-n)}\right)=\\
&=2\sum_{k=0}^{(n-1)/2}\binom{n}{k}(-1)^{k}\frac{e^{in(n-2k)}+e^{-in(n-2k)}}{2}=\\
&=2\sum_{k=0}^{(n-1)/2}\binom{n}{k}(-1)^{k}\cosh(in(n-2k))=\\
&=2\sum_{k=0}^{(n-1)/2}\binom{n}{k}(-1)^{k}\cos(n(n-2k)).
\end{align*}$$
It remains to study this as $n\to\infty$.


text:
Q: How to Create Indefinite Duration for a Task in Windows 2003 Task Scheduler I'm trying to create tasks with an indefinite duration. On Windows Server 2008, if I don't specify the duration, then the duration is assumed infinite. However, on Windows Server 2003 a duration must be specified (and be equal or greater than the interval). Currently, I am just setting the task to have a duration of a year if it is meant to repeat a long time.
Is there a way to specify an indefinite duration on Windows Server 2003?
if (m_TimeInterval.m_Expire.Year < 2099) //xp and win7 max year is 2099
    tTrigger.Repetition.Duration = m_TimeInterval.getDuration();
else if (!newVer) tTrigger.Repetition.Duration = m_TimeInterval.getInterval().Add(TimeSpan.FromDays(365));
tTrigger.Repetition.Interval = m_TimeInterval.getInterval();
tTrigger.Repetition.StopAtDurationEnd = true;

Notes:

*

*I am using the Task Scheduler API to add these task definitions.

*Interval and Duration are set by use of TimeSpans.

*newVer is false since I am working with Task Scheduler 1.1 and not 1.2 or higher

*tTrigger is of type TimeTrigger

A: I ended up using 1-1-2099 as 'indefinite'

A: You also can use TimeSpan.Zero which makes the task infinite.
Heres a short code snippet to demonstrate how to use it on a Trigger :
Trigger triggerTask = Trigger.CreateTrigger(TaskTriggerType.Time);
triggerTask.StartBoundary = DateTime.Now.AddMinutes(3);
triggerTask.SetRepetition(new TimeSpan(0, 3, 0, 0, 0), TimeSpan.Zero);

A: Can you use Duration.Forever.TimeSpan?


text:
Q: Filling a double[][] from the CSV file I have this CSV file:
World Development Indicators
Number of countries,4
Country Name,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014
Bangladesh,6.28776238,13.20573922,23.46762823,30.16828408,34.35334451,44.94535882,55.19256723,62.82023906,74.42964608,80.03535051
"Bahamas, The",69.21279415,75.37855087,109.340767,102.7875065,101.2186453,118.8292307,81.5628489,80.65383375,76.05187427,82.29635806
Brazil,46.31418452,53.11025849,63.67475185,78.5549801,87.54187651,100.8810115,119.0023853,125.0018521,135.3050481,138.9514906
Germany,94.55486999,102.2828888,115.1403608,126.5575074,126.2280577,106.4836959,109.6595675,111.5940398,120.9211651,120.4201855

I am trying to store countries' data(double once) into a matrix(double[][]). Here is the code that I have so far:
public double[][] getParsedTable() throws IOException {
    double[][] table = new double[4][10];
    String row;
    int indexRow = 0;
    int indexColumn = 0;
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    br.readLine();
    br.readLine();
    String line = br.readLine();
    while(line != null && !line.isEmpty()){
        line = br.readLine();
        String[] array = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);
        for(int i = 1; i < array.length; i++){
            table[indexRow][indexColumn] = Double.parseDouble(array[i]);
            indexColumn++;
        }
        indexColumn = 0;
        indexRow++;
    }
    System.out.print(Arrays.deepToString(table));
    return table;
}

I am getting an arror : NullPointerException at:
String[] array = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);

I cant figure out why. I tried different combinations. nothing seems to work. It seems to pick up the numbers from the CSV file and store them, but when I call:
System.out.print(Arrays.deepToString(table));

it does not print out anything, hence I cant check if its stored properly or not. Could you tell me: 1. Why I am getting an error. 2. Why System.out.println does not print out an array. Thanks

A: Arrays.deepToString is wrong.  You are passing in an array of primitives.  When you pass it in, you pass in double[][].  This is interpeted as Object[] where the objects are double[], so it will try to print double[] objects, and not print doubles.
One solution is to create an array Double[][].
Change
 double[][] table = new double[4][10];

to
 Double[][] table = new Double[4][10];

Autoboxing will convert each double to a Double.  Since Double is an object and not a primitive, deepToString will print out each Double individually.  If you read the javadoc for deepToString it explains that it operates recursively on arrays of reference type, not on primitive arrays.
If you want to stick with double[][]
for (int i = 0; i < table.length; i++) {
    for (int j = 0; j < table[i].length; j++) {
        System.out.print(table[i][j]);
        System.out.print(' ');
    }
    System.out.println();
}

A: In the csv, first 3 lines are not real country's data. So read in line-4 before while loop starts.
In while loop, first finish the processing of line string first. Eg: regular expression check & assign split data into table.
Then only read in next line at end of while loop, to be processed in next iteration.
Feel free to try this out:
public double[][] getParsedTable() throws IOException {
    double[][] table = new double[4][10];
    int indexRow = 0;
    int indexColumn = 0;

    // check whether you need to handle any exception for this
    BufferedReader br = new BufferedReader(new FileReader(fileName));

    String line = null;

    try {
        // line 1-3 are not real country's data
        br.readLine();
        br.readLine();
        br.readLine();

        // first country data begin at line 4
        line = br.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }

    while (line != null && !line.isEmpty()) {
        String[] array = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);

        for (int i = 1; i < array.length; i++) {
            table[indexRow][indexColumn] = Double.parseDouble(array[i]);
            indexColumn++;
        }

        indexColumn = 0;
        indexRow++;

        // read next line only at end of loop, not beginning of loop
        // line is ready to be processed at next iteration
        try {
            line = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    System.out.print(Arrays.deepToString(table));
    return table;
}

A: If we assume that name of a country will not contain a digit and country name and numbers will be only comma separated, then following can be done without regex. I have changed file reading a little bit because it can run into issues.
public double[][] getParsedTable() throws IOException {
    double[][] table = new double[4][10];
    int indexRow = 0;
    int indexColumn = 0;
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    br.readLine(); // ignore first line
    br.readLine(); // ignore second line
    br.readLine(); // ignore third line (contains title)
    String line;
    while (true) {
        line = br.readLine();
        if (line == null) break; // end of file reading

        int index = 0;
        while (true) {
            index = line.indexOf(",", index) + 1;
            if (Character.isDigit(line.charAt(index))) {
                break;
            }
        }

        // from index, line is expected to contain comma separated numbers
        String[] array = line.substring(index).split(",");
        for (int i = 0; i < array.length; i++) {
            table[indexRow][indexColumn] = Double.parseDouble(array[i]);
            indexColumn++;
        }
        indexColumn = 0;
        indexRow++;
    }
    System.out.print(Arrays.deepToString(table));
    return table;
}


text:
Q: Question about splitting the vertices up into pairwise connected trees Let $G=(V, E)$ be an undirected simple graph.
I couldn't find the formal definition, so let's call a subset $V'\subset V$ a chunk , if it's either a singular vertex or if every pair of it's vertices are connected by a path of vertices that all belong to $V'$. Thus a chunk can be represented as a singular vertex or a tree. We say that two disjoint chunks "touch" if there is an edge connecting  a vertex from one chunk  to a vertex from the other chunk. If this edge is also unique, then we say that the chunks touch uniquely.
My understanding is that  $G$ having the complete graph $K_n$ as minor, is equivalent to $G$ having $n$ disjoint chunks that are pairwise touching.
My question is: if $G$ has $n$ disjoint chunks that are pairwise touching, can we then also find $n$ disjoint chunks that are pairwise uniquely touching?
I have mostly looked at planar graphs and well known graphs like the Peterson to look for counterexamples, but could easily find n uniquely touching chunks in most of them. But I can't find a formal argument why this would be the case, nor a way to show it by induction. Do you think this is true, or can provide a counter example, let me know.
Thanks for your time!


text:
Q: Building a dynamic array of functions for Q.all() in Jscript I'm trying to to pass a variable number of functions into Q.all()
It works fine if I code the array manually - however I want to build it up in a loop as the system wont know how many times to call the function until runtime - and needs to pass a different ID into it for each AJAX call.
I've tried various methods with no success (e.g. array[i] = function() {func}) - I guess eval() could be a last resort.
Any help would be massively helpful.
// Obviously this array loop wont work as it just executes the functions in the loop
// but the idea is to build up an array of functions to pass into Q
var arrayOfFunctions = [];

for(var i in NumberOfPets) {
    arrayOfFunctions[i] = UpdatePets(i);
}

// Execute sequence of Ajax calls
Q.try(CreatePolicy)
.then(updateCustomer)
.then(function() {

    // This doesn't work - Q just ignores it
    return Q.all(arrayOfFunctions)

    // This code below works fine (waits for all pets to be updated) - I am passing in the ID of the pet to be updated
    // - But how can I create and pass in a dynamic array of functions to achieve this?
    // return Q.all([UpdatePets(1), UpdatePets(2), UpdatePets(3), UpdatePets(4), UpdatePets(5), UpdatePets(5)]);

    })
.then(function() {
    // do something
})
.catch(function (error) {
    // error handling
})
.done();

Thanks in advance.

A: Q.all doesn't expect an array of functions, but an array of promises. Use
Q.try(CreatePolicy)
.then(updateCustomer)
.then(function() {
    var arrayOfPromises = [];
    var numberOfPets = pets.length;
    for (var i=0; i<numberOfPets; i++)
        arrayOfPromises[i] = updatePet(pets[i], i); // or something
    return Q.all(arrayOfPromises)
})
.then(function() {
    // do something
})
.catch(function (error) {
    // error handling
});


text:
Q: how to use exists in this query? I have a patient called Joseph in a table.
I need to get the info of all doctors that attend him.
The database is like this:
Doctors table:
-ID
-NAME
-AGE
-SPECIALTY

Patient table:
-ID
-NAME
-AGE
-SICKNESS

Appointments:
-doctor_ID
-patient_ID
-DATE

It is mandatory that I use exists to get the data
Our work is the nearly the same as the answer given below. It goes like this
SELECT doctor.name, doctor.age
  FROM clinic.doctors
 WHERE EXISTS(SELECT *
                FROM clinic.appointments
               WHERE appointments.patient_ID = '1'
                 AND appointments.doctors_ID <> NULL
             )

A: Here's the general form for coordinating an exists:
SELECT *
FROM
  table_whose_records_I_want_to_know x
WHERE
  EXISTS(SELECT null FROM table_whose_records_might_relate_to_x y WHERE x.some_column = y.some_column)

Think of it like "for every record in X the DB will run the subquery using the values from that row in X, and if the subquery produces at least one row, then X's row will be present in the output. If the subquery produces no rows, then X row is not output". It doesnt matter what values the sub query selects - EXISTS merely cares whether the subquery produces any rows or not, not what values are produced
You thus need to make your query like "select all from doctors where there exists a row in apointments that has a doctor_id of the doctor's id and a patient_id of Z" where Z is the ID you claim to know

Edit: Just to make it absolutely super clear how the subquery is coordinated with the outer query table:

All the attempts you've posted that you've tried so far do not coordinate the subquery at all


text:
Q: se puede llenar un combobox Hola mi inquietud es si se puede llenar un combobox directamente desde un recordset sin tener que repasar item por item algo asi como:
me.combobox1.rowsource (el nombre del recordset)
y que muestre los resultados. Gracias

A: Si, crea tu consulta SQL, datos de conexión a la bbdd, etc. Luego declara un array (Dim arrData as variant) y mete en ese array todos lo que obtengas del recordset:
arrData = rs.GetRows

Ese array tendrás que transponerlo así:
Me.combobox1.list = application.transpose(arrData)

Aunque te recomiendo que para transponer matrices utilices esta función:
Function TransponerMatriz(arrData)

    Dim TempArray()
    ReDim TempArray(UBound(arrData, 2) + 1, UBound(arrData, 1) + 1) ' Note: VBScript is zero-based

    For i = 0 To UBound(arrData, 2)
    For j = 0 To UBound(arrData, 1)
        TempArray(i, j) = arrData(j, i)
    Next
    Next

    TransponerMatriz = TempArray

End Function

Con lo que quedaría así:
Me.combobox1.list = TransponerMatriz(arrData)

Saludos.

A: Prueba con cualquiera de estas tres formas:
me.combobox1.rowsource = "Nombre_Consulta"

me.combobox1.rowsource = "Nombre_Tabla"

me.combobox1.rowsource = "SELECT Campo1, Campo2 [, etc.] FROM Tabla;"


text:
Q: Flex4: Using httpService in consecutive function calls I have this button:
<s:Button includeIn="MeniuPrincipal" label="Descarcare Date" click="downloadLmData(event)"/>

and this click event handler:
protected function downloadLmData(event:MouseEvent):void
{
    downloadData('competenta', 'competente');
    downloadData('localitate', 'localitati');
}

the downloadData function looks like this:
private function downloadData(item:String, items:String):void
{
    try {
        var colVar:String   = 'col' + cappitalize(items);

        this.status = "Descarcare date in curs...";

        this[colVar] = null;

        var service:HTTPService = new HTTPService();
        service.url = serverUrl + items + '/xml';
        service.resultFormat = "xml";
        service.method = "GET";
        service.addEventListener(ResultEvent.RESULT, addArguments(downloadDataComplete, [item, items]));
        service.send();
    } catch (error:Error) {
        errorHandler.defaultErrorHandler(error);
    }
}

The problem is, all calls are ignored, except for the first one. Is there any "queuing" mechanism which would allow all calls to be made?
Thank you.

A: You need to chain your asynchronous calls. See these 2 blog posts for implementations :
http://kuwamoto.org/2006/05/16/dealing-with-asynchronous-events-part-1/
http://kuwamoto.org/2006/05/16/dealing-with-asynchronous-events-part-2/

A: I will rather use observer pattern. The easiest way.


text:
Q: Why Logistic Regression is not a generative model? I was reading about the difference between discriminative and generative models, and I read that Discriminative models learn only the boundary between classes hence they are not able to to create new datapoints.  The article states, if we use a generative algorithm, for instance naive bayes, we can create new data points from class "i" basically by choosing features that maximize P(X|Y=class i ). However; the point I did not understand is that could not we also do the same creating in a discriminative model.
Take logistic regression for instance, cannot we create a vector x that  maximizes P(Y=i|X=x) ? Would not this x vector would be our new sample , namely did not we generated a new sample ?

A: To elaborate on @Bayesian's (correct) answer, consider a logistic regression model where cases of diabetes ($y$) are predicted by sugar intake ($x$).
The model learns $P(y = 1 | x) = \text{logit}^{-1}(\alpha + \beta x)$ - that is, $P(\text{Diabetes}|\text{Sugar intake})$, but since it doesn't learn the distribution of sugar intakes in the population, $P(x)$, it can't generate samples from the distribution of diabetes cases, $P(y)$.

A: The fundamental difference between Generative Model and Discriminative Model is, one is learning about $ P(X,y) $ while discriminative model is learning $ P(y|X) $
According to this definition, Logistic Regression is not a generative model.
For your example "create a vector x that maximizes $ P(y=i|X=x)$ ", it was not a generative model at all. Since it still learn nothing about $ P(X,y) $
Taking a real life example, suppose we got a logistic regression model that predict whether the image is a photo of cat. (Usually this is CNN ,but the logic is the same)
The image $ X $ that maximize $ P(y= cat| X=x) $ is an image that consist of different feature of cats (e.g. tail, eyes) everywhere inside the image. Certain is maximize the probability of being classified as a cat, but you never see this image in reality. Mathematically speaking, if $ x^*  =argmax(P(y= cat| X=x))$ , $ P(x^*,y) $ can still be very low.


text:
Q: kernlab class prediction calculations failed => with SVMLinear NOT SVMRadial I got a problem training SVMLinear with caret. The data works just fine with SVMRadial though.
The data is accessible via (29/05/2016):
https://www.dropbox.com/s/ia2vc25uhxdgqn1/projetTest01.txt?dl=0
(8000 lines of 1021 variables, ~10% target)
Here's the code:
projetTest01<-read.table("projetTest01.txt", sep="\t")
Test01<-list(data=projetTest01[,-c(2,3)],label=projetTest01[,3])
Test01N<-Test01

Test01N$label<-as.factor(Test01$label)
levels(Test01N$label)[levels(Test01N$label)=="0"] <- "No"
levels(Test01N$label)[levels(Test01N$label)=="1"] <- "Yes"

temp<-as.matrix(Test01$data)
storage.mode(temp) <- "numeric"     #I need 'num' type
Test01N$data<-as.data.frame(temp)

svmTuneGrid_L <- data.frame(.C = 2^(-2:7))
trControl_SVML<-trainControl(method = "repeatedcv", repeats = 3, classProbs =  TRUE)
svmFit_Lin <- train(Test01N$label ~ ., data = Test01N$data,method = "svmLinear",preProc = c("center", "scale"), tuneGrid = svmTuneGrid_L,trControl = trControl_SVML)

And I got these messages:
line search fails [..]
Warning in method$predict(modelFit = modelFit, newdata = newdata, submodels = param) :
  kernlab class prediction calculations failed; returning NAs
Warning in data.frame(..., check.names = FALSE) :
  row names were found from a short variable and have been discarded
I looked up the site/the web for some answers, but

*

*the levels aren't numeric (=yes/no)

*the ClassProb is set to TRUE

*the labels can't be predicted perfectly from another variable (I know this from other algorithms)

*there isn't a empty class

*preproc(scale) or not doesn't make a difference

*And the data works just fine with SVMRadial!!

*I use caret 6.0-68

I really am at a loss. An idea someone?


text:
Q: always keep pseudo element horizontally in the middle How do I always keep a pseudo element horizontally in the middle? I have it positioned absolutely with a percentage value, which I undrstood was relative to the width of the element but on different screen sizes the circular "OR" is not consistently in the middle...
See below:

.content {
    display: flex;
    flex-direction: row;
    justify-content: space-evenly;
    text-align: center;
    margin: 20px;
}

.cc-content {
    width: 50%;
    padding: 5px 20px;
    position: relative;
    background-color: red;
}

.cc-content-1 {
  margin-right: 3px;
}

.cc-content-2 {
  margin-left: 3px;
}

.cc-content-1:after {
    content: 'OR';
    display: inline-block;
    position: absolute;
    vertical-align: middle;
    line-height: 60px;
    top: 20px;
    left: 90%;
    z-index: 1;
    font-size: 21px;
    font-weight: bold;
    border-radius: 100%;
    width: 60px;
    height: 60px;
    background-color: #F2F2F2;
    color: #006AAD;
}

Header Here

Lorem Ipsuom gshjgshj gshjgsajhusgs gsaiyusgisysgsyigs

Header Here

Lorem Ipsuom gshjgshj gshjgsajhusgs gsaiyusgisysgsyigs

If you resize the window you can see the circle shifts ever so slightly off cente, how do I always keep it in center with position absolute? Is not not percentage? I tried playing with flex since it is in a flex container but that doesn't seem to do anything.
How do I horizontally center a position absolute :after element?

A: Very similar to @mgrsskls but using actual :after element. Its an old trick to use absolute, then add left and negative margin equal to half-width. But in your case there is additional margin which needs to be thought of as well.

.content {
    display: flex;
    flex-direction: row;
    justify-content: space-evenly;
    text-align: center;
    margin: 20px;
}

.cc-content {
    width: 50%;
    padding: 5px 20px;
    position: relative;
    background-color: red;
}

.cc-content-1 {
  margin-right: 3px;
}

.cc-content-2 {
  margin-left: 3px;
}

.cc-content-1:after {
    content: 'OR';
    display: inline-block;
    position: absolute;
    vertical-align: middle;
    line-height: 60px;
    top: 20px;
    left: 100%;
    margin-left: -27px;
    z-index: 1;
    font-size: 21px;
    font-weight: bold;
    border-radius: 100%;
    width: 60px;
    height: 60px;
    background-color: #F2F2F2;
    color: #006AAD;
}

Header Here

Lorem Ipsuom gshjgshj gshjgsajhusgs gsaiyusgisysgsyigs

Header Here

Lorem Ipsuom gshjgshj gshjgsajhusgs gsaiyusgisysgsyigs

A: First of all I would put the "or" in the HTML, so screen readers would read it out loud correctly. Then you can position that element relative to the whole container, with percentage yes. You move it exactly to the middle with left: 50% and then by its half width back to the left with transform: translateX(-50%) (that way you don't have to know how wide the "or" element is).

.content {
    display: flex;
    flex-direction: row;
    justify-content: space-evenly;
    text-align: center;
    margin: 20px;
    position: relative;
}

.cc-content {
    width: 50%;
    padding: 5px 20px;
    position: relative;
    background-color: red;
}

.cc-content-1 {
  margin-right: 3px;
}

.cc-content-2 {
  margin-left: 3px;
}

.or {
    display: inline-block;
    position: absolute;
    vertical-align: middle;
    line-height: 60px;
    top: 20px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 1;
    font-size: 21px;
    font-weight: bold;
    border-radius: 100%;
    width: 60px;
    height: 60px;
    background-color: #F2F2F2;
    color: #006AAD;
    text-transform: uppercase;
}

Header Here

Lorem Ipsuom gshjgshj gshjgsajhusgs gsaiyusgisysgsyigs

or

Header Here

Lorem Ipsuom gshjgshj gshjgsajhusgs gsaiyusgisysgsyigs

A: Instead of left: 90%, you can do left: calc(100% - 30px).
30px is half the width of the pseudo-element.