text:
Q: Printing array element memory adresses C and C++, why different output?
Possible Duplicate:
How to simulate printf's %p format when using std::cout?

I try to print out the array element memory addresses in C and C++.
In C:
char array[10];
int i;
for(i =0; i<10;i++){
    printf(" %p \n", &array[i]);
}

I got the memory addresses: 0xbfbe3312, 0xbfbe3313, 0xbfbe3314, ....
But if I try to make the same in C++:
char array[10];
for(int i =0; i<10;i++){
    std::cout<<&array[i]<<std::endl;
}

I got this output:

�
P��
  ��
  �
k�
  �

Why is it different? Should I use the cout differently in C++ to print out the memory addresses? How should I print out the memory addresses?

A: The type of &array[i] is char*, and so cout<< thinks that you want to print a string.

A: std::cout does not necessarily treat pointers as pointers. A char* pointer could be a string, for instance. Taking the address of an element in a char array basically outputs the substring from that point.

A: You must cast &array[i] to void*
for(int i =0; i<10;i++){
    std::cout<<(void*)&array[i]<<std::endl;
}

This is because C++ streams work differently for different types. For example when you pass char* to it, your data is treated as a C-string - thus it is printed as a list of characters.
You must explicitly tell C++ that you want to print an address by casting.
By the way (void*) is not the best way to do that as you should avoid C-like casting. Always use C++-style casting (static_cast, dynamic_cast, reinterpret_cast). In this case static_cast would do the job.

A: Cast the address to void* before printing, in C++ the operator<< of ostream is overloaded for (const) char* so that it thinks it's a c-style string:
char array[10];
for(int i =0; i<10;i++){
    std::cout << static_cast<void*>(&array[i]) << std::endl;
}

Also see this answer of mine.


text:
Q: How to get true address of a shortened URL in PHP? Is there any way that I can get the URL pointed by another (shortened) URL?
For example, I have shortened http://www.stackoverflow.com to this URL: http://tinyurl.com/5b2su2
I need a function in PHP like:
getTrueURL($shortened_url)
{
 // ?
}

That should return 'http://stackoverflow.com' when getTrueURL('http://tinyurl.com/5b2su2') is called. How can I do this?
P.S:
If it is impossible in server-side, I can also use a JavaScript solution as well.

A: I think, you need this one:
<?php
function getTrueURL($url)
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_exec($ch);
    $data = curl_getinfo($ch);
    return $data["url"];
}

echo getTrueURL("http://tinyurl.com/5b2su2");
?>

A: <?php

function tinyurl_reverse($szAddress)
{
    $szAddress = explode('.com/', $szAddress);
    $szAddress = 'http://preview.tinyurl.com/'.$szAddress[1];
    $szDocument = file_get_contents($szAddress);
    preg_match('~redirecturl" href="(.*)">~i', $szDocument, $aMatches);

    if(isset($aMatches[1]))
    {
        return $aMatches[1];
    }

    return null;
}

echo tinyurl_reverse('http://tinyurl.com/5b2su2');
?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to convert column currency(USD and CAD) into one currency? I have one column containing "currency(USD and CAD)" and the other one is the currency value.
 How to create a new column that contains converted to USD values?
data = {'currency':['CAD', 'USD', 'CAD', 'USD'],'value':[20, 21, 19, 18]}
df = pd.DataFrame(data)

A: Create a mapping dict between USD and other currencies:
rates = {'CAD': 0.7849, 'EUR': 1.1322}
data = {'currency': ['CAD', 'USD', 'CAD', 'EUR'],
        'value': [20, 21, 19, 18]}

df = pd.DataFrame(data)
df['USD'] = df['currency'].map(rates).fillna(1) * df['value']
print(df)

# Output
  currency  value      USD
0      CAD     20  15.6980
1      USD     21  21.0000
2      CAD     19  14.9131
3      EUR     18  20.3796


text:
Q: A closed set in $\operatorname{Spec}(R)$ is irreducible iff $I(X)$ is prime
Let $R$ be a ring. Prove that a closed set $X\subseteq\operatorname{Spec}(R)$ is irreducible iff $I(X)=\bigcap_{p\in X}p$ is prime.

I proved $\rightarrow$. My attempt at $\leftarrow$ is as follows:
I assume for a contradiction that $X$ is reducible. I can then write $X=(V(I_1)\cap X)\cup(V(I_2)\cap X)$ with $V(I_1),V(I_2)\subseteq\operatorname{Spec}R$ closed sets. Since each of them is contained (and not equal) in $X$, I can find $p_i\in V(I_i)$ s.t $p_1\not\subseteq p_2$ and $p_2\not\subseteq p_1$. I know that in the finite case, that would mean that the intersection above would not be prime (it's easy to prove for two prime ideals and I guess you can inductively prove it for any finite number). But is it still true for any intersection? Otherwise, how can I get a contradiction?
Thanks in advance.

A: As you have assumed,
$$
X = (V(I_1) \cap X) \cup (V(I_2) \cap X)\\
\subseteq V(I_1) \cup V(I_2) = V(I_1 \cap I_2)
$$
The map $I$ is inclusion-reversing, so
$$
I_1I_2 \subseteq I_1 \cap I_2 \subseteq \sqrt{I_1 \cap I_2} = I(V(I_1 \cap I_2) \subseteq I(X)
$$
Since $I(X)$ is prime, $I_i \subseteq I$ for some $i$. But this implies $V(I_i) \supset V(I) = X$, and therefore $V(I_i) \cap X = X$, a contradiction.
The inclusion $I_1I_2 \subset I_1 \cap I_2$ can hardly be translated elegantly into similar property for $p_1$ and $p_2$. And Hilbert's Nullstellensatz is actually used. So I guess there is no simple solution following your idea.

A: Here is a way to prove what you want which tells you something "nice" about $X$, namely that $X$ is the closure of $\{I(X)\}$ in $\operatorname{Spec}(R)$.
First, prove that in any topological space, the closure of a point is an irreducible closed subset of that space. This is straightforward, and I leave this to you.
Next, observe that for any prime ideal $P$ of $R$, the closed subset $V(P)$ is the closure of the singleton $\{P\} \subset \operatorname{Spec}(R)$. Again, this is not so hard, and I leave this to you.
Onto your question. Since $X$ is a closed subset of $\operatorname{Spec}(R)$, $X = V(I)$ for some ideal of $R$. Since every prime $P$ in $X$ contains $I$, we have that $I(X)$ contains $I$, so $V(I(X)) \subset V(I)$. On the other hand, by definition of $I(X)$, every element of $V(I)$ contains $I(X)$, and so $V(I) \subset V(I(X))$, whence $V(I) = V(I(X))$. Since $I(X)$ is prime by hypothesis, the comments above complete the proof.

A: I think the main problem is that you tried phrasing the proof by contradiction. This is often unnecessary and seems to actually complicate the matter here. Let me first give a different approach.
Suppose that $\mathcal I(X)$ is prime. Then $X\ne\emptyset$ since $\mathcal I(\emptyset)=R$ is not prime. Now, consider some decomposition $X=X_1\cup X_2$ into non-empty closed sets. In order to show that $X$ is irreducible we have to show that one of $X_1,X_2$ is not proper (i.e. $X=X_1$ or $X=X_2$). Write $X_i=\mathcal V(I_i)\cap X$. Then
$$
X=X_1\cup X_2=(\mathcal V(I_1)\cup\mathcal V(I_2))\cap X\quad \implies \quad X\subseteq \mathcal V(I_1)\cup\mathcal V(I_2)=\mathcal V(I_1\cap I_2)
$$
by definition. Hence
$$
I_1\cap I_2\subseteq\mathcal I(\mathcal V(I_1\cap I_2))\subseteq\mathcal I(X)=I\,.
$$
But since $I$ is prime this implies that $I_1\subseteq I$ or $I_2\subseteq I$ concluding the proof.

Now on to your question: What theorem exactly are you referencing?


text:
Q: AWS MYSQL (mysqli_real_connect(): (HY000/2002)) : cannot allocate memory for the buffer pool I have a t2.small instance in AWS that has been running along for the better part of 10 months now without restarting the EC2 instance / the apache server / mysqld server and suddenly, as of a few minutes ago, it can't connect to the database.
I couldn't access any pages that connect to the database and attempting to login to phpmyadmin returns the error mysqli_real_connect(): (HY000/2002): No such file or directory
So while panicking, I did the following:

*

*Attempted to restart the mysql server with sudo service mysqld restart but it just kept coming up with STOPPED

*Restarted the EC2 instance

*It lives (for now until it crashes again)

Since it has crashed, I'd like to know why it crashed and how to prevent it from crashing again.
I dug into the mysqld.log and found below info:
Version: '5.6.39'  socket: '/var/lib/mysql/mysql.sock'  port: 3306  MySQL Community Server (GPL)
2019-06-17 14:08:19 15623 [Warning] Buffered warning: Performance schema disabled (reason: init fa
iled).

2019-06-17 14:08:19 15623 [Note] Plugin 'FEDERATED' is disabled.
2019-06-17 14:08:19 15623 [Note] InnoDB: Using atomics to ref count buffer pool pages
2019-06-17 14:08:19 15623 [Note] InnoDB: The InnoDB memory heap is disabled
2019-06-17 14:08:19 15623 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2019-06-17 14:08:19 15623 [Note] InnoDB: Memory barrier is not used
2019-06-17 14:08:19 15623 [Note] InnoDB: Compressed tables use zlib 1.2.8
2019-06-17 14:08:19 15623 [Note] InnoDB: Using Linux native AIO
2019-06-17 14:08:19 15623 [Note] InnoDB: Using CPU crc32 instructions
2019-06-17 14:08:19 15623 [Note] InnoDB: Initializing buffer pool, size = 128.0M
InnoDB: mmap(137363456 bytes) failed; errno 12
2019-06-17 14:08:19 15623 [ERROR] InnoDB: Cannot allocate memory for the buffer pool
2019-06-17 14:08:19 15623 [ERROR] Plugin 'InnoDB' init function returned error.
2019-06-17 14:08:19 15623 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2019-06-17 14:08:19 15623 [ERROR] Unknown/unsupported storage engine: InnoDB
2019-06-17 14:08:19 15623 [ERROR] Aborting
...
...(shutdown a bunch of plugins)
...
2019-06-17 14:08:19 15623 [Note] /usr/libexec/mysql56/mysqld: Shutdown complete

I searched around and found Inconsistent InnoDB Buffer Pool Size
https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/MySQL.KnownIssuesAndLimitations.html
Specifically, it details a solution to inconsistent buffer pool size by doing:
innodb_buffer_pool_chunk_size = 536870912
innodb_buffer_pool_instances = 4
innodb_buffer_pool_size = (536870912 * 4) * 8 = 17179869184

Questions:

*

*Have any of you encountered this? How did you go about solving it?

*What's actually happening to the server? Am I actually really running out of memory for mysqld as the logs say cannot allocate memory for the buffer pool? (I always do top from time to time to check and there's always at least half of it free.)

*Where did the above example from AWS get the number 536870912? And where do I put the lines? (/etc/my.cnf)?

Thank you for reading and any comments or suggestions.

A: 1) I encoutered the same problem and got it solved by following this.


text:
Q: How to I combine the results of multiple rules I have 3 roles and I am trying to return what actions a user can do based on the assigned roles.
Playground: https://play.openpolicyagent.org/p/5gN7ObojXh
The first part should check if the object being processed is in a list, and then if the role(s) return any actions.
I'm very new to OPA and Rego and I am finding it to be very confusing when anything more than simple comparisons are required.

A: Rules in OPA are either complete or partial. Complete rules are those that evaluate to a single value, and as such will fail if evalutated to different, conflicting values — e.g. a boolean "allow" rule can't be both true and false.
Partial rules either return sets or objects, and are built incrementally by evaluating each rule with the same name and adding the result to the set/object produced by the rule.
Example policy using a partial rule to build a set might look something like this:
package policy

import future.keywords.in

deny["Username found in deny list"] {
    input.user.name in data.users.denylist
}

deny[msg] {
    not "read" in input.user.roles
    msg := sprintf("User %v missing role 'read'", [input.user.name])
}

deny["/admin endpoint requires 'admin' role"] {
    input.request.path[0] == "admin"
    not "admin" in input.user.roles
}

When evaluated with an input like the below:
{
  "input": {
    "user": {
      "name": "bob",
      "roles": ["developer"]
    },
    "request": {
      "path": ["admin", "users"]
    }
  }
}

The deny rule might evaluate to:
[
  "User bob missing role 'read'",
  "/admin endpoint requires 'admin' role"
]

The example policy you provided could be rewritten to use incremental rules, like this: https://play.openpolicyagent.org/p/MYFFAVqMCu
If you'd like to learn more, the Styra Academy is a great complementary resource to the OPA docs.


text:
Q: How to unzip a password protected zip file in iOS?
Possible Duplicate:
unzip source code in Iphone
Obj-C, zip libary which will zip and unzip, with password protection?

I have a password-protected zip-file that contains a text file. I need to unzip it using a password and save the text file to a string. How to unzip in iOS?
IN KOREAN :
나는 한국 사람입니다. ios를 공부하고 있습니다.
Zipfile을 가지고 있습니다.
Zipfile은 암호를 가지고 있고, Zipfile안에 TxT파일이 있습니다.
암호가 있는 Zipfile의 암축을 해제하고, 그 안에 있는 Txt파일의 내용을 String에 넣고 싶습니다.
ios에서 압축을 해제하려면 어떻게 하나요?
알려주시길 부탁드립니다.

A: Look into gzip, libz.dylib. that is the library for compression i'm not sure if it supports password protected files but for compressing , decompressing files and strings it works grea, you should look into that


text:
Q: Problem with assigning values to complex variables using real() and imag() I want to assign a value (here 0.0f) to a complex variable which I defined first using std::complex<float>. The real and imaginary part of the variable should be then assigned using real(...)=0.0f and imag(...)=0.0f. But by compiling I get the error "lvalue required as left operand of assignment". I tried g++ 7.5 and also 6.5 and I got this error from both.
temp = new float[ nfft ];
  tempComplex = new std::complex< float >[ nf ];
  if ( processing->getComponentNSToProc() ) {
for ( int i = 0; i < sampNum; i++ ) {
  temp[ i ] = srcData[ iSrc ].rcvData[ iRcv ].dataNS[ i ];
  qDebug() << "before: temp[" << i << "] =" << temp[ i ] << "; ....dataNS[" << i << "] =" << srcData[ iSrc ].rcvData[ iRcv ].dataNS[ i ] << ";";
}
for ( int i = sampNum; i < nfft; i++ ) {
  temp[ i ] = 0.0f;
  qDebug() << "before: temp[" << i << "] =" << temp[ i ] << ";";
}
for ( int i = 0; i < nf; i++ ) {
  real( tempComplex[ i ] ) = 0.0f;
  imag( tempComplex[ i ] ) = 0.0f;

A: real, and imag, can be invoked without arguments, then they will return the read only real part or imaginary part of the object. If you call them with one argument then they will modify the real/imaginary part.
For instance
std::complex<float> z;
z.real(1.0f); // Sets the real part
x.imag(-2.0f); // Sets the imaginary part

A: For using a non-static member function of a class we need to use(call) it through an object of that class. So you can change your code to look like:
int main()
{

  std::complex<float> *tempComplex = new std::complex< float >[ 3];

  for ( int i = 0; i < 3; i++ )
  {

      tempComplex[i].real(0.0f);

      tempComplex[i].imag(0.0f);
      std::cout<<tempComplex[i]<<std::endl;
   }
}

The above code now works because tempComplex[i] is an object and we access the non-static member function named real and imag of the class std::complext<float>through this(tempComplex[i]) object.
Also after everything(at appropriate point) don't forget to use delete.


text:
Q: Kubernetes POD arguments are not passing to service, however Docker arguments are passing correctly
Problem Statement:
I have a created a Docker image successfully from docker.io/joethecoder2/spring-boot-web. It has been tested with command line arguments, and those work correctly locally with Docker.
I am trying to pass java arguments that are passed to Docker to a Kubernetes POD that is defined with a single image docker.io/joethecoder2/spring-boot-web
The purpose of passing the arguments is to let the POD know what the IP address and port number are for the database service.

Problem Definition:
I have defined a Kubernetes POD here, however I believe the arguments are not passed correctly from singlePod.yaml when the POD is running the service.
Expected Result:
I expect that the Kubernetes POD be compatible with the Docker image defined here.
I expect that the Kubernetes POD accept arguments just like Docker does here:

docker run -it -p 8080:8080 joethecoder2/spring-boot-web
  -Dcassandra_ip=127.0.0.1 -Dcassandra_port=9042

curl -X POST --header 'Content-Type: application/json' --header 'Accept: text/plain' 'http://localhost:8080/restaurant/arguments'

Correct result is returned-> 127.0.0.1:9042

Wrong Result:
I know that the actual arguments are not passed to the POD, because when I run the following service, I receive no arguments returned.
curl -X POST --header 'Content-Type: application/json' --header 'Accept: text/plain' 'http://192.168.64.3:32308/restaurant/arguments'

Wrong result is returned->   :
Expected result -> 127.0.0.1:9042, as defined in the singlePod.yaml file
Why are the arguments missing, even though the POD definition file knows that the arguments have been defined staticly?

A: If you want to inject environment variable into the container.It's better to use ConfigMap so it provides flexibility as well as separation of concern.
apiVersion: v1
kind: Pod
metadata:
  name: spring-boot-web-demo
  labels:
    purpose: demonstrate-spring-boot-web
spec:
  containers:
  - name: spring-boot-web
    image: docker.io/joethecoder2/spring-boot-web
    command: ["java","-jar", "spring-boot-web-0.0.1-SNAPSHOT.jar"]
  env:
  - name: DCASSANDRA_IP
    valueFrom:
        configMapKeyRef:
            key: Dcassandra_ip
            name: env-values
  - name: DCASSANDRA_PORT
    valueFrom:
        configMapKeyRef:
            key: Dcassandra_port
            name: env-values
  restartPolicy: OnFailure

---
apiVersion: v1
kind: ConfigMap
metadata:
  name: env-values
data:
  Dcassandra_port=9042
  Dcassandra_ip=127.0.0.1

Now You need to write a Service Manifest file to expose this container in order to access it.
I have attached links for further research.
ConfigMap
Service


text:
Q: Is the formula logically valid? (Predicate logic) I want to determine the following formula is logically valid or not?
I know that,

|I| = ω,
a^ I = 10,
P^ I (n) =  t, if n is prime, f,  otherwise,
Q^I (m, n) =  t, if m < n, f, otherwise

How can i find if the below formula is logically valid or not?
P(x) ⊃ ∃yP(y)

A: If you mean $\forall P(x) \rightarrow \exists P(y)$, then that is valid: since every object in the (non-empty!) domain has property $P$, there is of course going to be at least one thing in the domain that has property $P$.
But if you really meant for that formula to be $P(x) \rightarrow \exists y P(y)$, then that formula is not a sentence, and so it has no truth-value, and so it is not necssarily true either, which is what we typically mean by being 'logically valid'.
Then again, we could define a 'logically valid formula' as one that will be satisfied by every object of the domain, and then yes, it would be a logically valid formula, since given any object, if it has property $P$, then there is something with property $P$, and if it does not have property $P$, then the antecedent of the conditional would be false, and hence the conditional be true (to be exact, for any object $d \in D$, and where constant $c$ were to denote $d$ under the extended interpretation $I'$, the sentence $P(c) \rightarrow \exists y P(y)$ is always true). Which also means that $\forall x(P(x) \rightarrow \exists y P(y))$ is logically valid in the normal sense of the term.


text:
Q: Can I create a single file that mentions all files I want to build : c++ In React, I can write code like this for my containers/components:
export App from './App/App';
export Chat from './Chat/Chat';
export Home from './Home/Home';

This allows me to specify the stuff that I am exporting from that dir. Can I do something like that in CMake?
What I want is to be able to create a header file that includes the files that I want to build. I dont want to list them out in CMakeLists.txt as it becomes too cluttered. I also dont want to GLOB_RECURSE as it doesnt allow me to select files. How do I do this?

A: Just create file which lists sources:
sources.list:
foo.c
bar/baz.c

and read it using file(STRINGS) command into the variable:
CMakeLists.txt:
# Load list of sources into 'sources' variable
file(STRINGS "sources.list" sources)

# Use the variable
add_executable(my_exe ${sources})

As pointed by @wasthishelpful, a file used in file(STRINGS) is not tracked by CMake. That is, if content of the file will be modified(e.g., new sources will be added), explicit cmake call is needed to reflect this modification. (That is, simple make doesn't cause cmake to rerun).
Alternative to file(STRINGS), which force CMake to track file with sources. is include():
sources.cmake:
set(sources
    "foo.c"
    "bar/baz.c"
)

CMakeLists.txt:
# Run additional script, which fills 'sources' variable with list of sources
include(sources.cmake)

# Use the variable
add_executable(my_exe ${sources})

Such a way, if "sources.cmake" will be changed, cmake will be automatically rerun on make call.


text:
Q: Mac not re-waking networked PC I have a simple home network with 2 Macs, a Windows 7 PC, and an OpenELEC PC.
I sometimes watch media using VLC from the OpenELEC machine. It is set in such a way that it goes to sleep when possible which is perfect and as it should be.
When I turn on my Windows 7 PC, I browse the network and select the OpenELEC box. It tells me it can't connect, but after 5 or so seconds it starts working. This is because it has woken up and started being available on the network.
When I connect to an already-woken OpenELEC box from my Mac (one Mavericks / one El Cap) it connects right away and can start working with files on the network.
But if the OpenELEC machine goes to sleep even if the Mac is busy using its files, it stays asleep. I've had VLC die horribly because the underlying network suddenly isn't there anymore.
No amount of mucking about on the Mac seems to be able to get it to wake from a Mac. Windows > Linux will do it; Linux > Linux will do it; Mac > Linux won't do a thing.
How do I get a Mac to tell a remote network machine that has an active data stream not to go to sleep in the middle of using it?


text:
Q: Ubuntu 19.10 stuck at logo splash screen after update and recovery-mode also not working I had Ubuntu 19.04 in my MSI GL63 and I switched to Intel from Nvidia server settings for battery saving.
Everything was working fine until I decided to switch it back to NVIDIA. It asked me to reboot my system after which I encountered a black screen right after login.
I tried many fixes including purging all Nvidia related files and reinstalling the drivers and system upgrades but nothing worked.
Ubuntu 19.10 had been released and I decided to upgrade from TTY by CTRL+ALT+F2 hoping it would work. But now I don't even reach the login screen and it is stuck at the Ububtu logo with 5 dots.
I tried running recovery mode but only command line root access works. I even uncommented WaylandEnable=false in /etc/gdm3/custom.conf in vi editor.
I also tried to remove Nvidia drivers by sudo apt-get remove --purge nvidia-*
I also edited the GRUB file by adding nomodeset and nomodeset=0 but nothing works.
I have a dual booted system with Windows 10 Pro.
GPU - NVIDIA Geforce GTX 1050


text:
Q: Positioning cursor in between of text in WPF Based on some characters I need to position cursor in between the text or at the end of text when the user clicks on to that textbox control in WPF. Any idea how to achieve this?

A: NumberOfDigits.CaretIndex = Where you want it to be
So you gotta find out at which position these "characters" are.

A: Set the CaretIndex to the end of input like this :
TextBoxName.CaretIndex = TextBoxName.Text.Length - 1;

or to the middle of text like this :
TextBoxName.CaretIndex = TextBoxName.Text.Length / 2;


text:
Q: How to compile a java project with a terminal/cmd I got tired of using Eclipse because it was too "plain" and "old style". So I moved on to a program called Sublime Text 3 and I used a package named "material theme" which made the program look flat and all nice and stuff.
But I wanted to code Java in that but I don't know how to compile stuff without using an IDE and it was not easy to find out but I found out that you could do it through the terminal/cmd of your operating system.
But what I don't understand is how I could actually use the javac command which means Java Compile and I searched and I didn't find out because I couldn't understand anything that was posted on either YouTube or Stack Overflow because I'm new to this whole terminal/cmd Java Compiling thing.

A: You're almost there buddy!
Just be sure you have the Java Development Kit (JDK) installed in your system. The JDK provides you the command javac -which you need to compile your .java program files.
The javac command is not that friendly as you think it is. You have to let it know where to find the java file you want to compile.
For example you saved Main.java inside C:\Projects\Java you must compile it this way javac C:\Projects\Java\Main.java.
Then you can run your program this way too java C:\Projects\Java\Main
As mentioned here... You can find a more detailed explanation to the official tutorial.

A: You need to install java JDK which you can find here
Then you need to right-click on my computer->properties->advanced system settings->Environment variables -> Click on path -> New
Then add the path to the bin folder inside the install folder for JDK.
Then in cmd you can compile with
javac *.java

inside the directory of your code

A: *

*Install JDK
(Make sure your PATH variable is set up)

*Use SublimeText's Build System, which allows you to compile open java documents with the Ctrl + B command.

A: You did not install JDK. You need to install JDK which has javac command.
Installing JDK on MAC instructions
Installing JDK on Windows instructions
After installing JDK(Java Development Kit), you can run the command javac -version on command line and let it show the version that is installed.


text:
Q: OS X libstdc++ prevents boost::thread from interruptions? Consider the following sample code which creates a thread and interrupts it from the main thread using thread::interrupt call:
#include <iostream>
#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include <boost/ref.hpp>

int main()
{
    boost::thread t([]{
        int counter = 0;

        while (1){
            std::cout << "interruption enabled " << boost::this_thread::interruption_enabled() << std::endl;
            try {
                counter++;

                if (counter % 5 == 0)
                    throw std::runtime_error("runtime error!");

                std::cout << "thread function\n";
                boost::this_thread::sleep_for(boost::chrono::milliseconds(300));
            }
            catch (boost::thread_interrupted &interruption)
            {
                std::cout << "oops!.. time to finish!" << std::endl;
                return;
                //std::cout << "...but couldn't o_O..." << std::endl;
            }
            catch (std::exception &e)
            {
                std::cout << "some exception: " << e.what() << std::endl;
            }
        }
    });

    boost::this_thread::sleep_for(boost::chrono::milliseconds(3000));
    t.interrupt();
    std::cout << "joinable: " << t.joinable() << std::endl;
    if (t.joinable())
        if (!t.try_join_for(boost::chrono::milliseconds(500)))
        {
            std::cout <<"still RUNNING\n detach it..." << std::endl;
            t.detach();
        }

    std::cout << "main thread\n";
    boost::this_thread::sleep_for(boost::chrono::milliseconds(500));

    return 0;
}

Now, when compiled on OS X 10.10.3 like this (libc++ is used by default):
g++ main.cpp -I<path_to_boost_1_54_0> -std=gnu++11 -lboost_thread-mt -lboost_system-mt -lboost_chrono-mt -L<path_to_boost_1_54_0>/stage/lib
the output shows that interruptions are enabled:
interruption enabled 1
thread function
interruption enabled 1
thread function
...

If, however, one will use libstdc++:
g++ main.cpp -I<path_to_boost_1_54_0> -std=gnu++11 -stdlib=libstdc++ -lboost_thread-mt -lboost_system-mt -lboost_chrono-mt -L<path_to_boost_1_54_0>/stage/lib
I get the output which tells me that interruption are disabled:
interruption enabled 0
thread function
interruption enabled 0
thread function
...

Is there a reason for such behaviour? I used boost v1.54.0 and this LLVM v6.1.0:
$ g++ -v
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.1.0 (clang-602.0.49) (based on LLVM 3.6.0svn)
Target: x86_64-apple-darwin14.3.0
Thread model: posix

Thanks

A: I've reproduced this on linux:

*

*with gcc 4.8, 4.9 it works

*with clang 3.5 and libstdc++ it works
interruption enabled 1
thread function
interruption enabled 1
thread function
interruption enabled 1
thread function
interruption enabled 1
thread function
interruption enabled 1
some exception: runtime error!
interruption enabled 1
thread function
interruption enabled 1
thread function
interruption enabled 1
thread function
interruption enabled 1
thread function
interruption enabled 1
some exception: runtime error!
interruption enabled 1
thread function
interruption enabled 1
thread function
joinable: 1
oops!.. time to finish!
main thread

*with clang 3.5 and libc++ it doesn't work:
interruption enabled 128
thread function
oops!.. time to finish!
joinable: 1
Segmentation fault (core dumped)

This issue should be reported at the boost list, in my opinion.
There is a chance that the boost devs will indicate it's a bug in libc++


text:
Q: Spring Security bypass URL or Filter I have a Spring Boot application that is only exposing a REST API. I need to secure it and I'm using a token-based approach ― specifically JWT.
So far, this is what I have implemented:
//
// The Spring Security configuration class
@EnableGlobalAuthentication
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(final HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .authorizeRequests()
          .antMatchers("/api/login", "/api/logout").permitAll()
          .antMatchers("/api/**").authenticated()
          .anyRequest().authenticated()
        .and()
          .addFilterBefore(new JwtFilter(), BasicAuthenticationFilter.class)
          .sessionManagement()
          .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
  }
}

//
// The JWT filter class to check for the token in the HTTP request (headers)
public final class JwtFilter extends GenericFilterBean {
  private final Logger logger = LoggerFactory.getLogger(this.getClass());

  @Override
  public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws
      IOException, ServletException {
    final HttpServletRequest req = (HttpServletRequest)request;
    final String header = req.getHeader("Authorization");

    logger.debug("{} {}", req.getMethod(), req.getRequestURI());
    if ((null == header) || !header.startsWith("Bearer ")) {
      logger.debug("Missing or invalid Authorization header");
    }
    try {
      // Check the token here; the implementation is not relevant here
      /*SecurityContextHolder.getContext()
          .setAuthentication(manager.authenticate(new JwtToken(JWTParser.parse(header.substring(7)))));*/
      chain.doFilter(request, response);
    } catch (final AuthenticationException e) {
      SecurityContextHolder.clearContext();
      // Do some other stuff here
    } catch (final ParseException e) { /* ... */ }
  }
}

The issue is that the filter executes correctly for every single URI, but I want to be able to exclude some endpoints from the same set. My API is placed in this context /api/* and I want to exclude, for instance, /api/login and /api/logout.
NOTE: My Spring Boot application.yml file doesn't have settings to enable/modify any security-related features.

A: Filters will be executed for all the endpoints that are configured through HttpSecurity. If you do not want filters to be applied for certain endpoints, include them in a method that configures WebSecurity. For example,
@Override
public void configure(WebSecurity web) throws Exception {
    web
      .ignoring()
        .antMatchers("/api/login", "/api/logout");
}

Please read this post for more details.

A: I am doing the same as mentioned in the solution
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors()
        .and().csrf().ignoringAntMatchers("/api/auth/**").disable()
        .exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
        .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and().authorizeRequests()
        .antMatchers("api/content/**").permitAll()
        .anyRequest().authenticated();

        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("api/auth/signup");
    }

Every signup request is still hitting the doFilterInternal() method which was is a custom method.
While running EnableWebSecurity in debug mode i get :

Security filter chain:
[WebAsyncManagerIntegrationFilter
SecurityContextPersistenceFilter
HeaderWriterFilter
CorsFilter
LogoutFilter
AuthTokenFilter
RequestCacheAwareFilter
SecurityContextHolderAwareRequestFilter
AnonymousAuthenticationFilter
SessionManagementFilter
ExceptionTranslationFilter
FilterSecurityInterceptor ]

What should i do to solve this ?


text:
Q: Find all combinations of advanced filter criteria I've searched extensively and found plenty of information on permutations, but I can't think of a good way to adapt them. Its frustrating because I don't think the answer is that hard but I can't seem to get there on my own.
I am trying to convert a range of cells containing Selection Criteria into a range that Advanced Filter can read.  The range of selection criteria looks like this:

The problem is, Advanced Filter is evaluating each row as a separate filter set.  The logic looks something like this:
[awake AND bob AND cat AND earth AND yes] OR [sleeping AND sally AND dog AND earth AND yes] OR ... OR [martha].

This is the way Advanced Filter is supposed to work, but I need it to work like autofilter where I'd go through each field and check each filter criteria.  The logic should look like this:
[awake OR sleeping] AND [bob OR sally OR george OR martha] AND [cat OR dog OR bird] AND [earth] AND [alive]

After reading the documentation and multiple forums, the only way to do this I can find is to generate on separate rows every combination of the selection criteria possible.  The new range of selection criteria should look like this:

I've tested this by manually setting up the selection criteria range and it works properly, but I cannot figure out the code to automate it.  Here's what I've done so far - it starts off ok but soon starts repeating and missing certain permutations:
   If UBound(numRows) > 1 Then

    With Worksheets("fltr")
        .Range(.Cells(4, 1), .Cells(4, UBound(numRows))).Copy Destination:=Worksheets("afltr").Range("A1")
    End With

    'Determine number of rows needed for Advanced filter
    numPermute = numRows(1)
    For dstCol = 2 To UBound(numRows)
        numPermute = numPermute * numRows(dstCol)
    Next dstCol

    'Copy all permutations to advanced filter
    For dstCol = 1 To UBound(numRows)
        If thisRow > numRows(dstCol) Then
        thisRow = 2
        For thisGrp = 1 To numRows(dstCol)
            andSpltPos = 1
            For numRepeat = 1 To numPermute / numRows(dstCol)
                sbstFltrItms = Worksheets("fltr").Cells(4 + thisGrp, dstCol).Value 'MOD Problem?
                Worksheets("afltr").Cells(thisRow, dstCol).Value = sbstFltrItms
                thisRow = thisRow + 1
            Next numRepeat
        Next thisGrp
    Next dstCol

End If

Would really appreciate some help either generating the correct permutations or making the Advanced Filter work some other way.

A: This worked for me. I put the sheet in "show formula" mode (Ctrl+~) so you can see the formulas...
List to filter is in A7:B14, criteria range is A3:B4.

After applying the filter I just get one row ("B", "val2").


text:
Q: Energy method for damped wave equation vs heat eq. The textbook I using is Strauss's partial differential equations.
I don't understand how to find the energy formula for different pdes. It seems that the textbook does not give a general method to find the energy. For example, in the textbook it shows for string $\rho u_{tt}=Tu_{xx}$ the energy is $E=\frac12 \int^{\infty}_{-\infty}(\rho u^2_t+Tu^2_x)dx$ as below.(first picture).
But in exercise it asks for the damped string equation $u_{tt}-c^2u_{xx}+ru_t=0$, show that the energy decreases. I don't understand why the pde changes, the energy still is $E=\frac12 \int^{\infty}_{-\infty}(\rho u^2_t+Tu^2_x)dx$?
And the in the book it derives energy for diffusion equation in a totally different. (second picture)
It seems that one can define energy whatever they like, but that cannot be true. So I am really confused about what the "energy" means in energy method, and how to find the formula for the energy in different pdes.
first picture

second picture

A: For the proposed wave equations, an energy can be derived by multiplication of each term through $u_t$ and integration over $x$ in $\Bbb R$. In fact, integration rules give on the one hand
$$
\int u_t u_{tt} \,d x = \frac{d}{dt} \int \tfrac12 u_{t}^2 \,dx  ,
$$
and on the other hand
$$
\int u_t u_{xx} \,d x = -\frac{d}{dt} \int \tfrac12 u_{x}^2 \,d x  .
$$
Applying this process to the damping term $u_t$ yields a signed quantity:
$$
\int u_t^2 \,d x \geq 0 .
$$
So if we consider the damped wave equation $u_{tt} - c^2 u_{xx} = -r u_t$ with $r\geq 0$, we find
$$
 \frac{d}{dt} \int \tfrac12 [u_t^2 + c^2 u_x^2] \, d x = -r \int u_t^2 \,d x \leq 0 .
$$
The left-hand side represents the time derivative of an energy, while the negative quantity in the right-hand side represents dissipation. The damping term with coefficient $r$ influences dissipation, but it does not modify the expression of energy. Note that energy is a non-negative decaying function of time for all $r\geq 0$.
Essentially, the derivation of the energy for the wave equation is very similar to the case of the heat equation, but there is no rule in general. In analytical mechanics, we call Hamiltonian PDEs the partial differential equations that can be derived from an "energy" (more precisely, from a Hamiltonian density). The derivation of dissipation inequalities from physical ground principles is the subject of thermodynamics.


text:
Q: Randomly splitting a dynamic range into equal groups I have a dynamic range of values that I want to split into N groups, where N is specified by the user.
I want to do the following:

*

*Split the group into N equal parts.

*Specify which ones in the range that are to be in separate groups.

*Have a "checker" to see if the math works out and it is possible to do (i.e. a group of 11 cannot be split into 2 groups).

Here is a scenario:

*

*I have a list of 26 values (an array of letters, A to Z).

*I want two groups, randomly split.

*I specified 2 of the values where I want them to be separate (i.e. the letter B and X).
This should give me two groups, 13 values of "Group 1" and 13 values of "Group 2".
"Group 1" can contain something like ("B", "N", "V", "C", "T", ..... x 13)
"Group 2" contains ("X", "A", .... x 13)
The variables in this case are the # of values, # of groups to split, and specific values to split.
EDIT: google sheet example:
https://docs.google.com/spreadsheets/d/1baZr8QAkFjw1UwsMOyphma6v_MNkWz-aCLx57yPsViE/edit#gid=1454808593

A: try:
=ARRAYFORMULA(IF(B4<>TRUE,,TRANSPOSE(SPLIT(FLATTEN(QUERY(QUERY(QUERY({
 ROUNDUP(SEQUENCE(COUNTA(B7:B))/(COUNTA(B7:B)/B2)),
 SORT({RANDARRAY(COUNTA(B7:B)), FILTER(B7:B, B7:B<>"")})},
 "select max(Col3) group by Col2 pivot Col1"), "offset 1", 0),,9^9)), " "))))

UPDATE:
=ARRAYFORMULA(IFNA(CHAR(96+VLOOKUP(B7:B, {QUERY({B7:B,
 COUNTIFS(C7:C, C7:C, ROW(C7:C), "<="&ROW(C7:C))*C7:C}, "where Col2<>0");
 {FILTER(B7:B, C7:C=FALSE, B7:B<>""), QUERY(SORT({RANDARRAY(SEQUENCE(B1-B2)),
 ROUNDUP(SEQUENCE(B1-B2)/B3), QUERY({
 COUNTIFS(C7:C, C7:C, ROW(C7:C), "<="&ROW(C7:C))*C7:C, B7:B},
 "select Col2 where Col1=0 and Col2 is not null")}), "select Col2")}}, 2, 0))))


text:
Q: How to use find_in_set() function in Codeigniter to find more than one values from the database field which was stores as comma seperated values How to use find_in_set() function in Codeigniter to find more than one values from the database field which was stored as a comma seperated values

A: The MySQL function find_in_set() can search only for one string in a set of strings.
This can help you
$this->db->where('CONCAT(",", `columnname`, ",") REGEXP ",(val1|val2|val3),"');


text:
Q: Write list to specific column in csv I'm trying to write the data from my list to just column 4
namelist = ['PEAR']

for name in namelist:
    for man_year in yearlist:
        for man_month in monthlist:
            with open('{2}\{0}\{1}.csv'.format(man_year,man_month,name),'w') as filename:
                writer = csv.writer(filename)
                writer.writerow(name)
                time.sleep(0.01)

it outputs to a csv like this
P             E                 A                R

4015854     234342            2442343            234242

How can I get it to go on just the 4th column?
                                                        PEAR

4015854     234342                2442343              234242

A: Replace the line writer.writerow(name) with,
writer.writerow(['', '', '', name])

A: When you pass the name to csvwriter it assumes the name as an iterable and write each character in a column.
So, for getting ride of this problem change the following line:
writer.writerow(name)

With:
writer.writerow([''] * (len(other_row)-1) + [name])

Here other_row can be one of the rest rows, but if you are sure about the length you can do something like:
writer.writerow([''] * (length-1) + [name])

A: Instead of writing '' to cells you don't want to touch, you could use df.at instead. For example, you could write df.at[index, ColumnName] = 10 which would change only the value of that specific cell.
You can read more about it here: Set value for particular cell in pandas DataFrame using index


text:
Q: smooth scrolling with link inside svg, or rescaling text, what should I try? I'm creating a website using an SVG as header/nav.
At first I created the hyperlink text inside the svg, like this:

        <text transform="matrix(1 0 0 1 495 160)"
        font-family="'Ubuntu'" font-size="22">Contact</text>

but when I added a jquery scroll to it, I found out that that doesn't work on xlinks.
To fix this I decided to make the text have absolute positioning to overlay the svg, adding this to my style:
#menu {
    position:absolute;
    top:25%;
    left:60%;
    width:100%;
}

and have the items as list:

Welkom

Missie

Links

I've got it to work, but only on a 1980px wide window, because the svg as a whole rescales and the text doesn't follow the same pattern.
http://fiddle.jshell.net/78eh5u52/9/show/
But I prefer the way the "contact" button is showing, since that rescales along with the svg, but as you can see in the fiddle the smooth scroll effect doesn't apply to that
There should be two ways to fix this: I either revert to placing the text inside the svg and find a way to get the scroll effect working on that. Or I figure out how to make the text size and position scale exactly like the underlying svg (svg on top of svg?)
Which way would you advice me to try to fix this and what should I look into?
here's my full code:
http://jsfiddle.net/78eh5u52/9/

A: You can stick with the svg to make your links smooth-scroll. Instead of using jquery smooth-scroll you can just write your own custom function that does the scrolling. And that you can easily call from your svg.
Your jquery function could look like this. You can just embed it into your html with script-tags:
function scrollTo(target){
  $('html,body').animate({
    scrollTop: $(target).offset().top
  }, 1000);
  return false;
}

And then you can call this from the svg like this:

  <text transform="matrix(1 0 0 1 495 160)"
  font-family="'Ubuntu'" font-size="22">Contact</text>

Notice the top. in the code, so it can find your function. Finally, if you want to have the mousecursor changed, you should add some css:
.link {
  cursor: pointer;
}


text:
Q: Simple django filter is includes all users' data rather than that of the logged-in user I'm new to Django and have built a basic filter that does not filter according to the logged-in user's data but rather all users' data, which is incorrect. The filter is for an Automation class, which has a many:many relationship with the Message class (and funnily enough the exact same happens with the message filter).
Views.py:
@login_required(login_url='login')
@allowed_users(allowed_roles=['admin', 'customer'], own_account_only=True)
def automation_list(request, pk):
    account = Account.objects.get(id=pk)
    automations = account.automation_set.all()
    filter = AutomationFilter(request.GET, queryset=automations)
    automations = filter.qs
    context = {'account': account,
               'automations': automations, 'filter': filter}
    return render(request, 'automations/automation_list.html', context)

Filters.py:
class AutomationFilter(django_filters.FilterSet):
    start_date = DateFilter(field_name='date_joined', lookup_expr='gte')
    end_date = DateFilter(field_name='date_joined', lookup_expr='lte')

    class Meta:
        model = Automation
        fields = '__all__'
        exclude = ['account', 'date_created']

Models:
class Automation(models.Model):
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=200)
    account = models.ForeignKey(Account, on_delete=models.CASCADE)
    date_created = models.DateTimeField(auto_now_add=True, null=True)
    messages = models.ManyToManyField(Message, blank=True)

    def __str__(self):
        return self.name

class Message(models.Model):
    name = models.CharField(max_length=100)
    subject = models.CharField(max_length=128)
    text = models.TextField()
    account = models.ForeignKey(Account, on_delete=models.CASCADE)
    date_created = models.DateTimeField(auto_now_add=True, null=True)
    automations = models.ManyToManyField('automations.Automation', blank=True)

    def __str__(self):
        return self.name

Why is the filter not just filtering according to the logged-in user? I'd have thought that I'm only passing in the user's data via this line:
filter = AutomationFilter(request.GET, queryset=automations)

Thanks


text:
Q: Html.EditorFor SelectList With the introduction of Html.EditorFor everything just seems easier -- All but one thing: EditorFor<SelectList>
What would be the best way to make it work? What I need is either a checkboxlist, a dropdownlist or the like.
I can easily find mvc1 solution for the problem, but mvc2 seems to not be there.
Any thoughts?

A: You could use the templating available - See ScottGu's post on it http://weblogs.asp.net/scottgu/archive/2009/07/31/asp-net-mvc-v2-preview-1-released.aspx


text:
Q: Create serverfolder if filepath does not exist I have a controller method that handles file uploads from a jquery script. I specify the filepath with the following code Path.Combine(Server.MapPath("~/UserFiles/"), qqfile); I would like to add a parameter that specifies a subfolder for the file, but i can only specify existing folders.
Is there any easy fix to create the subfolder on the server if it doesn't exist?
This is my controller method:
public ActionResult FileUpload(string qqfile)
{
    var file = string.Empty;

    try
    {
        var stream = Request.InputStream;
        if (String.IsNullOrEmpty(Request["qqfile"]))
        {
            // IE
            HttpPostedFileBase postedFile = Request.Files[0];
            stream = postedFile.InputStream;
            file = Path.Combine(Server.MapPath("~/UserFiles/"), System.IO.Path.GetFileName(Request.Files[0].FileName));
        }
        else
        {
            //Webkit, Mozilla
            file = Path.Combine(Server.MapPath("~/UserFiles/"), qqfile);
        }

        var buffer = new byte[stream.Length];
        stream.Read(buffer, 0, buffer.Length);
        System.IO.File.WriteAllBytes(file, buffer);
    }
    catch (Exception ex)
    {
        return Json(new { success = false, message = ex.Message }, "application/json");
    }

    return Json(new { success = true }, "text/html");
}

A: Have you tried this?
        string path = "~/UserFiles/subfolder/";
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        //todo

Or this should work
string folder= "subfolder";
var path= Server.MapPath("~/UserFiles/" + folder);
var directory = new DirectoryInfo(path);
if (directory.Exists == false)
{
    directory.Create();
}
//todo


text:
Q: My network service (netsvcs) seems to be hogging all my memory Before everyone goes complain that I should wait for Windows 10, don't. Because I'm sure high school/university assignments will NEVER get a 2-4 month extension.
Operating System: Windows 7, Service Pack 1 Home Premium
Laptop Model: Acer Aspire 5742
CPU: Intel(R) Core(TM) i3-370M, clocked at 2.4Ghz
RAM: 2GB (2x 1GB DDR3 sticks), true value is about 1.9GB.
I'm sure you don't need to know everything else..

Basically this (not the worse) happens:

It can at times get up to 1.4GB, but you get the idea.
My network service seems to be using a lot of memory, even when there are no programs that require network access open. And by 'a lot', I meant at least 50% to all of my avaliable RAM (1.4GB at most, without any other program running), to the point that all my applications would crash and the computer would hang for up to two hours until netsvcs actually died down back to the '50% of avaliable memory range'.
This problem persists even when the computer is not connected to a network, and sometimes happens at startup (after logging in), and it happens every 30 minutes, for about 20 minutes during the entire duration that the computer is turned on (and a user is logged in).
What seems to be wrong? (I'll post a picture when I can)


text:
Q: Element with key 'surv.xgboost' not found in DictionaryLearner I am using R version 3.6.3, mlr3 version 0.3.0 and mlr3proba version 0.1.6 (the latest development versions I could find) and xgboost version 0.90.0.2 → I am trying to use the command: lrn("surv.xgboost")
but I receive the error message:
Error: Element with key 'surv.xgboost' not found in DictionaryLearner! Did you mean 'classif.xgboost' / 'regr.xgboost'?

Please let me know if you would like me to provide any further details concerning the issue.

A: Thanks for your interest in mlr3proba :) The xgboost learner is currently in limbo between mlr3proba and mlr3learners, as of tomorrow you can simply run
install.packages("mlr3learners")
library(mlr3learners)
lrn("surv.xgboost")

but until then please instead run
remotes::install_github("mlr-org/mlr3learners#135")
library(mlr3learners)
lrn("surv.xgboost")


text:
Q: Merging the same combination of columns I have a table that looks like this:

Further down in the table, the countries in Target.Country are repeated in Source.Country, therefore repeating the combinations but with different numbers, sums and means. Is it possible for when the combinations are the same, sum the remaining columns together and add an additional column to find the average?
For example:
Source.Country Target.Country number   sum_intensity   mean_intensity
North Korea     South Korea    26492     10674.9         0.402
South Korea     North Korea    34912     53848.3         1.542

To be:
Source.Country Target.Country  number  sum_intensity mean_intensity  Average
North Korea     South Korea     61404   64523.2         1.944         1.05

Any help would be great!

A: A similar solution to what @Axeman proposed in the comments:
library(purrr)
library(dplyr)
df=data.frame(Source.Country=c('North Korea', 'South Korea'),
              Target.Country=c('South Korea', 'North Korea'),
              number=c(26492, 34912),
              sum_intensity=c(10674.9, 53848.3),
              mean_intensity=c(0.402, 1.542))

df %>% mutate(grp = purrr::map2_chr(Source.Country, Target.Country, ~paste(sort(c(as.character(.x), as.character(.y))), collapse=' '))) %>%
    group_by(grp) %>%
    summarise(number = sum(number),
    sum_intensity = sum(sum_intensity),
    mean_intensity = sum(mean_intensity),
    average = sum_intensity/number)

# # A tibble: 1 x 5
#   grp                     number sum_intensity mean_intensity average
#   <chr>                    <dbl>         <dbl>          <dbl>   <dbl>
# 1 North Korea South Korea 61404.        64523.           1.94    1.05

A few minor tweaks:

*

*it does require collapse in the paste command

*needs as.character to prevent the country names from being coerced into integers

*mean_intensity can't be used as an output in the summary, then as an input, but an average of averages doesn't make much sense when number is unbalanced anyway. I just recalculated the average from the sums

A: I increased the dataframe to check if the code was working properly
df1<-rbind(c( "North Korea ","South Korea" ,       26492 ,    10674.9 ,
0.402), c(   "South Korea",  "North Korea"  ,  34912  ,   53848.3   ,      1.542),
c( "Canada ","South Korea" ,       26492 ,    10674.9 ,        0.402),
c(   "South Korea",  "Canada"  ,  34912  ,   53848.3   ,      1.542))
colnames(df1)<-c("Source.Country",  "Target.Country",  "number",  "sum_intensity",
"mean_intensity")
df1<-data.frame(df1)

df1$number<-as.numeric(as.character(df1$number))
df1$sum_intensity<-as.numeric(as.character(df1$sum_intensity))
df1$mean_intensity<-as.numeric(as.character(df1$mean_intensity))

df1$Countries<-apply(cbind(df1$Source.Country, df1$Target.Country), 1, function(x)
paste(sort(x), collapse=" "))

#
library(reshape)
m1 <- aggregate(df1$number~df1$Countries,data=df1,FUN=mean)
m2 <- aggregate(df1$sum_intensity~df1$Countries,data=df1,FUN=mean)
m3 <- aggregate(df1$mean_intensity~df1$Countries,data=df1,FUN=mean)

mvtab <- merge(rename(m1,c(y="number")),
               rename(m2,c(y="sum_intensity")))

mtab2<-merge(mvtab, rename(m3,c(y="mean_intensity")))


text:
Q: How to run command from variable instead of those line in python? I have below commands for run az aks command:
from azure.cli.core import get_default_cli
az_cli = get_default_cli()
res = az_cli.invoke(['login', '--service-principal', '-u', client_id, '-p', client_secret,'--tenant',tenant_id])
az_cli.invoke(['aks','command','invoke','--resource-group',resourcegroup,'--name',clustername,'--command','kubectl apply -f',outfile_final])

I want as below,
azcmd = "az login --service-principal -u " + client_id + " -p " + client_secret + " --tenant " + tenant_id

**res = az_cli.invoke([azcmd])**

but Above script is giving error like args should be a list or tuple,
and 2nd error:

Is there anyways to run invoke with get input from variable.
Edit1:
I'm applying deployment file as below:
namespace = "kubectl apply -f abc.yaml"

A: I tried in my environment and got below results:
Initially I tried with same command and got same error:

I installed azure-cli module in my local machine, Also instead of using -
res = az_cli.invoke([azcmd])

You can add your azcmd inside ([ ])
from  azure.cli.core  import  get_default_cli
az_cli = get_default_cli()
cmd=(['login', '--service-principal', '-u', client_id, '-p', client_secret,'--tenant',tenant_id])

res=az_cli.invoke(cmd)

Is there anyways to run invoke with get input from variable.

With above code I can invoke with get input from variable.
Console:

Reference:
Authenticating Azure CLI with Python SDK - Stack Overflow by Jim Xu.


text:
Q: Example of an algebraic number of degree 4 that is not constructible  The number $b:=\frac{\sqrt{2a}+\sqrt{4\sqrt{a^2-3}-2a}}{2}$ with
    $a:=\frac{\sqrt[3]{18+2\cdot\sqrt{65}}}{2}+\frac{2}{\sqrt[3]{18+2\cdot\sqrt{65}}}$ is a root of the irreducible polynomial $x^4-6x+3$.The algebraic number $a$ is a root of the irreducible polynomial $2x^3-6x-9$ and therefore not constructible with ruler and compass.
I claim that $b$ isn't constructible either. If this is the case, how can this be shown?

A: As explained in the comments, one needs to check if the splitting field of $x^4-6x+3$ has degree equal to a power of $2$ or not. The resolvent cubic of this polynomial equals $x^3-12x+36$ which is irreducible (over $\mathbb{Q}$), because it has no root modulo $7$. Hence the splitting field in question contains a subfield of degree $3$, so it cannot have degree equal to a power of $2$. This shows that $b$ is not constructible. You can read about the resolvent cubic here.


text:
Q: SQL query is correct but still a "SQL error 1064" appears I can't deal with it. I'm experiencing big troubles with this very query:
UPDATE books
SET books.out = books.out + 1
WHERE id = 81813130;

UPDATE books
SET books.available = 0
WHERE books.in = books.out;

If I run it on my phpMyAdmin, everything's fine and everything completes, but in my CakePHP application this query doesn't work and when I perform a debug this is what I'm told:

Warning (512): SQL Error: 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE books SET books.available = 0 WHERE books.in = books.out' at line 1**

I'm calling my query from a controller:
$this->Lending->update_lendings($this->data['Lending']['book_id']);

and the actual query is of course into the model:
$query = "
    UPDATE books
    SET books.out = books.out + 1
    WHERE id = ".$id.";

    UPDATE books
    SET books.available = 0
    WHERE books.in = books.out;
          ";

I really can't say why this isn't working. It seems that error 1064 Mysql is a very common question in here but I didn't find anything useful about my very issue.
I steadfastly thank you for your support and help.

A: It looks like your problem might be due to PHP's lack of support for Multiple Statement Execution. Multiple Statement Execution allows you to run two queries in a single request and receive multiple result-sets in response.
MySQL DOES support it, but the default setup in PHP prevents this (that is, if you're using the deprecated mysql_connect() era functions). This is actually a nice default because there are some serious bugs that can be introduced by allowing multiple-queries (see SQL injection).
So, the solution could be to alter your code to request the data separately.
$query = "
UPDATE books
SET books.out = books.out + 1
WHERE id = ".$id.";";

mysql_query($db, $query);

$query = "UPDATE books
SET books.available = 0
WHERE books.in = books.out;";

mysql_query($db, $query);

That being said, if you think that it's safe enough to use multi-statements (that is, if all of the input values are sanitized), then go ahead and try to use the mysqli functions (there not even deprecated!).
mysqli_multi_query( $query ) should give you the flexibility you need.

A: aparently, it's because you use reserved words in your query, try and escape all table names and table columns in ``
list of reserved words in mysql available here

A: If the second Update statement is meant to change only the row that the first statement updated, then you could use a single Update:
UPDATE books
SET out = out + 1
  , available = CASE WHEN in = out
                       THEN 0
                       ELSE available
                END
WHERE id = 81813130


text:
Q: In R, how do you define a new column in a df as a function of a subset of another column? I have time series data in a data frame. Let's say I have one column of dates, one column of values, and I want to create a new column that is the sum of all values before the date index. Is there a better solution than using a for loop?
For example:
table = data.frame(date=seq(1,5),values=c(3,2,4,1,5))
table$sum = ...??

A: For this you can use cumsum:
table = transform(table, sum_value = cumsum(values))
table
  date values sum_value
1    1      3         3
2    2      2         5
3    3      4         9
4    4      1        10
5    5      5        15


text:
Q: If value exsists, update Ok, I have a table where I will collect users devices. When a user logs in, I want it to register the device, if it already exists, it would just want to update the timestamp. This is only when a user logs in.
The table looks like this:
device_id => BIGINT AUTOINCREMENT PRIMARY KEY
user_id => BIGINT FOREIGN KEY users(id)
device_name => VARCHAR(40) (Will be like 'Donald ducks iphone')
device_type => VARCHAR(10) (Will be defined by the client, like "IOS")
last_usage => TIMESTAMP (On update, new timestamp and all that)

So, when a user logs in, I have the user_id, device_name, device_type.
What I want:
if the id, name and type already exists in a row, just update timestamp, else insert the values.
Since this has nothing to do with the primary key I dont know how to do this. Of course I could do something like first select these values, return that and do the update/insert afterwards, but this does not feel right :)

A: You can use REPLACE in MySQL 5.0+:

REPLACE works exactly like INSERT, except that if an old row in the
  table has the same value as a new row for a PRIMARY KEY or a UNIQUE
  index, the old row is deleted before the new row is inserted

Example:
REPLACE INTO TableName (user_id, device_id, device_name, device_type, last_usage) VAULES (1, 2, "Test Device Name, "Test Type", NOW());

A: First, make device_name and device_type unique.
Now you have a couple of options. You can use:
INSERT IGNORE INTO devices (...) VALUES(...)

or if you're worried important errors might get ignored, use:
INSERT INTO devices (...) VALUES(...)
ON DUPLICATE KEY UPDATE device_id = device_id

Note that this is different from REPLACE in that this doesn't affect the old records at all, whereas REPLACE will create a new ID and timestamp.
EDIT: Since you now want to update the timestamp, use:
INSERT INTO devices (...) VALUES(...)
ON DUPLICATE KEY UPDATE last_usage = NOW()

A: For Each r In Me.Lstbox_Tables.ItemsSelected

'Create a recordset with required data

sql = "SELECT * FROM " & Me.Lstbox_Tables.ItemData(r)

'tablename = "Gahpp00d_" + rs!Table_Name

Set rs = db.OpenRecordset(sql, dbReadOnly)

Dim SheetName As String

SheetName = Replace(Me.Lstbox_Tables.ItemData(r), "GAHPP00D_", "")

On Error Resume Next

excelWbk.Sheets(SheetName).Select

If Err.Number <> 0 Then

MsgBox Err.Number & ":" & Err.Description, vbCritical, "ERROR!!!"

MsgBox "Worksheet " & SheetName & " doesn't exist.", vbCritical, "Sheet Missing!!!"

excelWbk.Close False

appExcel.Quit

 Exit Sub

 End If

A: You may need to convert this to mysql as its mssql but something along the lines of:
declare @count int
declare @user varchar
declare @machine varchar
declare @type as varchar

select @count = (select count(*) from [table] where user = @user and machine=@machine and type=@type)

if @count = 0
begin
insert into
[table]
select
@machine,
@user,
@type,
current_timestamp
end

if @count > 0
begin
update
[table]
set timestamp = current_timestamp
where
machine = @machine
and
user = @user
and
type = @type
end

Regards,
Marcus


text:
Q: Can't figure out why syntax error near "from" is appearing for sqldf in R I'm trying to compare subject IDs between columns to find unique IDs. I keep on getting a syntax error even though I've spent the past hour checking and re-checking my syntax. I decided to make a simple data frame to play around with an low and behold I get the same error.
Here my syntax for the proxy data frame
color <- c('yellow', 'red', 'green', 'blue')
number <- c(1,3,4,5)
stuff <- data.frame(color, number)

sqldf('select number, from stuff where color = red')

Here's the error I got

Error in sqliteSendQuery(con, statement, bind.data) : error in
  statement: near "from": syntax error

I'm beyond frustrated that I can't get this simple query to work. What gives?
I even tried removing the comma before 'from' and then I get the following error.

Error in sqliteSendQuery(con, statement, bind.data) :    error in
  statement: no such column: red

A: Remove commas and change quotes:
> stuff
   color number
1 yellow      1
2    red      3
3  green      4
4   blue      5

> sqldf("select number from stuff where color = 'red'")
  number
1      3


text:
Q: Compare two hash arrays in ruby except a key I have two hash arrays like this:
hashArray1 = [{"id"=>"1","data"=>"data1"},{"id"=>"2","data"=>"data2"}]
hashArray2 = [{"id"=>"3","data"=>"data1"},{"id"=>"4","data"=>"data2"}]

I want to compare both of them and return true if everything else matches without the "id" key.
I have tried something like this:
hashArray1.each do |h1|
  hashArray2.each do |h2|
    if h1.select{|h| h!= "id"} == h2.select{|b| b!= "id"}
      break
    else
      return false
    end
  end
end

But this seems to be incorrect. Does anyone have a better solution. I am on plain ruby 1.9.3, not using rails framework.

A: I would simply do:
hash1.zip(hash2).all? do |h1,h2|
  return false unless h1.keys == h1.keys
  h1.keys.each do |key|
      return false if h1[key] != h2[key] unless key == 'id'
  end
end

A: If hash1.length != hash2.length then you can bail out immediately as they can't be the same. If they have the same length then you could do something like this:
except_id = ->(h) { h.reject { |k, v| k == 'id' } }
same = hash1.zip(hash2).find { |h1, h2| except_id[h1] != except_id[h2] }.nil?

If same is true then they're the same (while ignore 'id's), otherwise they're different. Using Hash#reject is one pure Ruby way to non-destructively look at the Hash without a particular key. You could also use:
except_id = lambda { |h| h = h.dup; h.delete('id'); h }

if "copy and remove" makes more sense to you than filtering. If you don't like find then all? might read better:
same = hash1.zip(hash2).all? { |h1, h2| except_id[h1] == except_id[h2] }

or even:
same_without_id = lambda { |h1, h2| except_id[h1] == except_id[h2] }
same == hash1.zip(hash2).all?(&same_without_id)

A: The question is not necessarily clear, but I assume the order of the hashes are taken into account.
hash1.map{|h| h.reject{|k, _| k == "id"}} ==
hash2.map{|h| h.reject{|k, _| k == "id"}}


text:
Q: How to delete system files in Windows 7? When I first started testing windows 7 RTM, I created a separate partition for it. That left me with a vista partition (carrying all my personal files and stuff), and a windows 7 partition. When 7 came out, I ended up doing a clean install on the second partition (the one that had the RTM version) instead of upgrading the vista installation.
Now I have all my files stored in a large partition, and windows 7 installed on a smaller partition, which is perfect. Problem is: vista is still installed on the large partition, and it takes up quite a lot of space. When I boot into 7 and try to remove the system files from the vista partition, I click through the usual UAC prompt, but then I get a notification saying:
"You need permissions from XXX to perform this action."
Where XXX is the name I had given to the PC in the vista installation. And my only options are "Try Again" or "Cancel".
Booting a Ubuntu live CD might do, but I was hoping for a way to do it directly from Seven, I'm just that lazy. =P
So: How can I erase windows system files that are on a different partition (and belong to another installation)?
Backing up my Personal files and formating the vista partition would take way too long, there are quite a lot of files.
Wow, that was a long question. Thanks to those who read all of it.
UPDATE:It seems that taking ownership of the files should solve the problem, but my "Take Ownership" right-click-menu option isn't reaching inside the folders. That would force me to take ownership of the files one by one. Does anyone know the command to take ownership of everything inside a folder?

A: You need to "take ownership" of the files. How to Geek method. Or use Ultimate Windows Tweaker to add this facility and a bunch of other stuff.


text:
Q: Create SQL statement from MongoDB request I am migrating from MongoDB to PostgresDB and I have a request to mongo that I am having a hard time updating. Can someone help either transform this into a sequelize statement or a plain SQL query?
find(num: int) {
(await this.collection).aggregate(

[{
            $match: {
                id : num,
                active: true
            }
        }, {
            $lookup:
                {
                    from: 'list-database',
                    pipeline: [{
                        $match: {
                            id: num,
                            type: 'in',
                            active: true
                        }
                    }],
                    as: 'helper.in'
                }
        }, {
            $lookup:
                {
                    from: 'list-database',
                    pipeline: [{
                        $match: {
                            id: num,
                            type: 'out',
                            active: true
                        }
                    }],
                    as: 'helper.out'
                }
        }])}

I tried tranforming it into this
where: {
    id: num,
    active: true
},
include: [
    {
        model: sequelize.models['list-database'],
        where: {
            id: num,
            doorType: 'inbound',
            active: true
        },
        as: 'helper.in',
        required: false
    },
    {
        model: sequelize.models['list-database'],
        where: {
            id: num,
            doorType: 'outbound',
            active: true
        },
        as: 'helper.out',
        required: false
    }]
});

But it does not work. The two databases are not linked together


text:
Q: Pythonic way to distinguish read-only function input parameters from mutable ones Python doesn't seem to have a valid const qualifier per How do I create a constant in Python? What would be the most "pythonic" way for differentiating read-only / mutable function parameters? Should I just point it out in the comments?
# my_graph is READ-ONLY
# my_set is added items with property X ...
def my_lovely_function(my_graph,my_set):

A: In C and several other languages, typically real outputs are communicated via inputs that are passed by pointers or by reference. The reason for this is that the return value mechanism in many of these paradigms has been hijacked for error handling purposes i.e. return value is a success/error code while useful outputs are populated in an input/pointer reference. This has led for the need to denote some inputs as being untouchable (consts) and others as being touchable to prevent confusion in using the function.
Python typically doesn't want you to do things that way. It wants you to use Exceptions and exception handling for error handling and to use return statements for actual outputs. This is cleaner and more in line with the original idea of return values before they were highjacked by error handling.
In some cases, it is still more convenient to use a mutable input to transfer data out. Everything in python is always by reference. This is fine except if the calling context doesn't want you, the function, to modify the variable it provided as an input.
Python's solution is to 1) expect the function writer to properly document inputs, outputs, and side-effects on mutable inputs, and 2) provide the calling context the option of passing in immutable objects if they want to ensure those objects will not be changed.
So if you have a list and you don't want some function you call to add or subtract things from it, pass in the information as a tuple instead. No function will be able to add or subtract anything to your tuple, however they might be able to change elements of the tuple if those are mutable. Instead of a set, pass a frozenset. There is no immutable dict type, but you can get around that by passing a copy or translating it to a frozenset of tuples. Strings, ints, floats, and complex numbers are all immutable. Note that mutable objects embedded in immutable containers can still be changed. If this is undesired, then make sure they are immutable. Alternatively, if you are paranoid, you can call copy.deepcopy() on an object to make a totally independent copy (recursively) to pass into the function. Any changes at any nested level of this deep copy will not affect the original object.
When writing a function, it should be clear from the documentation (preferably docstring) or the code itself what the return values and side effects on mutable objects are. Using docstrings to capture this when writing a function is best practice.
When calling a function, you should defensively make use of immutable types (or deep copying if need be) as needed for your specific circumstances.


text:
Q: Xamarin Android: What is the correct way to Marshal a string from C# to a Unicode string in C++? I am writing a Xamarin Android app and trying to also write a C++ native library that the Xamarin app needs to pass data to. I need to pass a Unicode string to the library, but I am getting some strange behavior when I try.
In my native shared library, I have the following code:
extern "C" void logANSI(const char* data) {
  __android_log_print(ANDROID_LOG_INFO, "StringMarshaling", "ANSI data: %s", data);
}

extern "C" void logUnicode(const wchar_t* data) {
  __android_log_print(ANDROID_LOG_INFO, "StringMarshaling", "Unicode data: %ls", data);
}

On the C# side, I have the following DllImport declarations:
[DllImport("StringMarshaling", EntryPoint = "logANSI", SetLastError = true, CharSet = CharSet.Ansi, ThrowOnUnmappableChar = true)]
public static extern void LogANSI([MarshalAs(UnmanagedType.LPStr)] string data);

[DllImport("StringMarshaling", EntryPoint = "logUnicode", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern void LogUnicode([MarshalAs(UnmanagedType.LPWStr)] string data);

Then I have the following code in my Activity:
  StringMarshaling.LogANSI("12345");
  StringMarshaling.LogUnicode("12345");

In the log output, I see:
05-17 18:07:12.437  Unitech PA700 Info  8351  StringMarshaling  ANSI data: 12345
05-17 18:07:12.437  Unitech PA700 Info  8351  StringMarshaling  Unicode data: 1

How can I get the full string, and not just the first character?

A: __android_log_print accepts a char *, so:
Using this C/C++ function:
extern "C" void logUnicode(const wchar_t* data) {
    std::wstring fooStr = std::wstring(data);
    __android_log_print(ANDROID_LOG_INFO, "StringMarshaling", "Unicode data: %s", fooStr.c_str());
}

With this DllImport:
[DllImport("StringMarshaling", EntryPoint = "logUnicode", SetLastError = true)]
public static extern void LogUnicode(string data);

Calling:
StringMarshaling.LogUnicode("12345");

Will result in:
[StringMarshaling] Unicode data: 12345


text:
Q: How to check if two branches changed the same line (automatically) Imagine that we created two branches from master, branch1, and branch2.
How could we detect using git that branch1 and branch2 changed the same line?
We do not care about intermediate commits in the new branches. We just need to check the difference between branch1 and master and the differences between branch2 and master and check if they changed any common line.
Thanks in advance.
Ps: we cannot cherry-pick all the commits in the branches in order to detect possible conflicts, this approach would produce false positives.

A: If you want to view the diffs, you can compare :
git diff master...branch1    # three dots

and
git diff master...branch2

Say branch1 (resp. branch2) forked from master at commit c1 (resp. c2).
You could try to apply the changes brought by branch1 on top of c2, and see how this compares with the content of branch2.
Here is one way to do that :
# create a temporary branch 'tmp1' starting at the same commit as branch1
git checkout -b tmp1 branch1

# squash all history to one single commit
git reset --soft c1
git commit -m "branch1 content"

# replay that commit on top of c2 :
git checkout -b tmp2 c2
git cherry-pick tmp1

# you can now compare tmp2 and branch2 :
git diff tmp2 branch2


text:
Q: Is there a way to start a MySQL server outside of the command line on Windows? I am about to begin teaching a class on SQL to people with no programming experience. At the start of the class, I want to offer guidance on installing and using MySQL in the simplest way possible. I am using a Mac, but want to be able to help students with Windows computers as well. On Mac, to start the server I can simply go to System Preferences > MySQL > Start MySQL Server to start the server. Is there an equivalently similar way of doing things on Windows, or does it need to be done in the command line?
I have seen videos where people have gotten a server to run in MySQL Workbench just by clicking on a MySQL connection instance on the startup page, but I have not been able to do that unless I have already run the server from System Preferences first.
It has been difficult to figure this out without access to a Windows machine to try this on. So, is there a similar way of starting a MySQL server on Windows through some sort of system preferences GUI as can be done on Mac?

A: Enter Services in type here to search box, open,scroll down to find mysql right click and left click start,
for the long explanation  https://dev.mysql.com/doc/refman/8.0/en/windows-start-service.html

A: We can start from the service available with the windows. To start from the service we can follow bellow steps.
METHOD #1: Access the Installed Service

*

*Open up the Services icon in the Control Panel

*Scroll alphabetically to the MySQL service

*Right click the service

*Click Start Service


text:
Q: Is It An Inner Product
Let $C^{1}[0,1]$ be the vector space of all continuous functions   $f:[0,1]\to \mathbb{C}$ with continuous derivative on $[0,1]$
$\newcommand\inner[2]{\left\langle #1, #2 \right\rangle}$
$$\inner{f}{g}=f(0)\overline{g(0)}+f'(0)\overline{g'(0)}+f(1)\overline{g(1)}$$

*

*Is it an inner product over the subspace $P_{2}=\mathrm{span}\{1,x,x^2\}$?

*Is it an inner product over $C^{1}[0,1]$?

I have started with
a.$$\overline{\inner{g}{f}}=\overline{g(0)\overline{f(0)}+g'(0)\overline{f'(0)}+g(1)\overline{f(1)}}=f(0)\overline{g(0)}+f'(0)\overline{g'(0)}+f(1)\overline{g(1)}=\inner{f}{g}$$
b.$$\inner{\alpha f+\beta g}{h}=[\alpha f(0)+\beta g(0)]\overline{h(0)}+[\alpha f(0)+\beta g(0)]'\overline{h'(0)}+[\alpha f(1)+\beta g(1)]\overline{h(1)}=\alpha f(0)\overline{h(0)}+\alpha f'(0)\overline{h(0)}+\alpha f(1)\overline{h(1)}+\beta g(0)\overline{h(0)}+\beta g'(0)\overline{h'(0)}+\beta g(1)\overline{h(1)}=\alpha\inner{f}{h}+\beta\inner{g}{h}$$
Which hold for both $1$ and $2$
Looking at $\inner{f}{f}$ for the first case we get:
$$\inner{f}{f}=[f(0)]^2+[f'(0)]^2+[f(1)]^2$$ Which is greater than $0$ and equal to $0$ if each element is zero $f(0)=f(1)=f'(0)=0$ and it can be only if $f\equiv 0$
Looking at $\inner{f}{f}$ for the second case we get:
$$\inner{f}{f}=|f(0)|^2+|f'(0)|^2+|f(1)|^2$$ Which is greater than $0$ and equal to $0$ if each element is zero $|f(0)|=|f(1)|=|f'(0)|=0$ and it can be only if $f\equiv 0$
So it is an inner product from both $1$ and $2$? If we know that a function is an inner product on a "bigger" space let say bigger dimension vector space, can we conclude it will an inner product for all subspaces of the vector space?

A: No, your second case is not correct. There are $C^1$-functions with $f(0)=f(1)=f'(0)=0$ but $f\neq 0$, e.g. $f(x)=x^3-x^2$. The rest looks good.

A: No, it is not an inner product in $\mathcal{C}^1\bigl([0,1]\bigr)$. Take $f(x)=x^2-x^3$. It is not the null function, but $\langle f,f\rangle=0$.

A: Your belief that $\lvert f(0) \rvert = \lvert f'(0) \rvert = \lvert f(1) \rvert = 0$ implies that $f \equiv 0$ is incorrect in general. For example, a smooth bump function centered at $1/2$ with support within $[1/4, 3/4]$ is a nonzero function whose every derivative is zero at both $0$ and $1$. This shows that the second case is not true.
This also shows that you should revisit this step in the first case. Is this true for degree $2$ polynomials? This is something that needs to be shown.

A: To prove that $\newcommand\inner[2]{\langle #1, #2 \rangle}$$\inner{f}{f} = 0$ implies $f = 0$ on the space $\mathrm{span}\{1,x,x^2\}$, consider $f \in \mathrm{span}\{1,x,x^2\}$. $f$ must be of the form $f(x) = ax^2 + bx + c$. The conditions imposed on the coefficients $a, b, c$ by $\inner{f}{f} = 0$ are:
$$0 = f(0) = c$$
$$0 = f(1) = a+b+c$$
$$0 = f'(0) = 2a$$
From here follows $a = b = c = 0$, which implies $f = 0$.

A: If $\newcommand\inner[2]{\langle #1, #2 \rangle}$$f \in P_2$ and if $\inner{f}{f}=0$, then $f\equiv 0$. This is true ! But you have not proved it !
Let $f(x)=x^2(x-1)$. Then $\inner{f}{f}=0$, but we do not have that $f\equiv 0$.
Conclusion: $\inner{\cdot}{\cdot}$ is not an inner product on $C^1[0,1]$.


text:
Q: Redshift JDBC vs ODBC drivers performance To connect to the AWS Redshift we can use JDBC or ODBC drivers. Recently I have heard that the JDBC drivers performance is about 40% better than ODBC ones. Unfortunately, I cannot find such information somewhere in the documentation.
Do you have any experiences which drivers perform better on AWS Redshift?

A: There may be minor differences in query execution time for different driver types due to the following:
https://docs.aws.amazon.com/redshift/latest/dg/c_challenges_achieving_high_performance_queries.html#compiled-code

The execution engine compiles different code for the JDBC connection protocol and for ODBC and psql (libq) connection protocols, so two clients using different protocols will each incur the first-time cost of compiling the code. Other clients that use the same protocol, however, will benefit from sharing the cached code.

Note that first time compilation cost has been dramatically reduced in recent Redshift releases.


text:
Q: Many-to-many recursive relation I'm trying to add many-to-many recursive relation within given entity in entity framework. My problem is that I can't add additional properties in the table "MyEntityTable". Here is the code snippet:
modelBuilder.Entity<MyEntity>()
.HasMany(a => a.ParentTransportUnits)
.WithMany(b => b.ChildTransportUnits)
.Map(mc => { mc.ToTable("MyEntityTable");
mc.MapLeftKey("ParentColumn");
mc.MapRightKey("ChildColumn"); });

Any suggestion is appreciated!
Thanks in advance


text:
Q: Only one expression can be specified in the select list when the sub-query is not introduced with EXISTS SELECT
  ( Select
COUNT(t2.ID) as Total_HH_Memebers_Primary,t1.SETTLEMENT_ID
from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
WHERE  EXISTS (SELECT 1
               FROM   PScData t1
               WHERE  t1.SETTLEMENT_ID = SETTLEMENT_ID
                AND t2.EDUCATION_LEVEL = 5
               HAVING Count(*) > 1)
               Group By t1.SETTLEMENT_ID
) col1

  , (Select
COUNT(t2.ID) as Total_HH_Memebers_Secondary,t1.SETTLEMENT_ID
from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
 WHERE  EXISTS (SELECT 1
               FROM   PScData t1
               WHERE  t1.SETTLEMENT_ID = SETTLEMENT_ID
                AND t2.EDUCATION_LEVEL = 10
              HAVING Count(*) > 1)
               Group By t1.SETTLEMENT_ID

) col2

Here is my query, i want to get two different results based on "WHERE" condition from same table in the form of columns when i do this its giving this error .can somebody how to it correctly?

A: Use conditional aggregation:
SELECT
    SUM(CASE WHEN t2.EDUCATION_LEVEL = 5
             THEN 1 ELSE 0 END) AS Total_HH_Members_Primary,
    SUM(CASE WHEN t2.EDUCATION_LEVEL = 10
             THEN 1 ELSE 0 END) AS Total_HH_Members_Secondary,
    t1.SETTLEMENT_ID
FROM PScData t1
INNER JOIN PscMemberData t2
    ON t2._PARENT_AURI = t1.URI
GROUP BY
    t1.SETTLEMENT_ID
HAVING COUNT(*) > 1;

The two subqueries in the select clause look totally unnecessary to me.  And also I think we can remove the EXISTS clause, and move the HAVING clause to the outer query.

A: Try With cte
;with col1 as
(  Select
COUNT(t2.ID) as Total_HH_Memebers_Primary,t1.SETTLEMENT_ID
from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
WHERE  EXISTS (SELECT 1
               FROM   PScData t1
               WHERE  t1.SETTLEMENT_ID = SETTLEMENT_ID
                AND t2.EDUCATION_LEVEL = 5
               HAVING Count(*) > 1)
               Group By t1.SETTLEMENT_ID
),col2 as
(Select
COUNT(t2.ID) as Total_HH_Memebers_Secondary,t1.SETTLEMENT_ID
from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
 WHERE  EXISTS (SELECT 1
               FROM   PScData t1
               WHERE  t1.SETTLEMENT_ID = SETTLEMENT_ID
                AND t2.EDUCATION_LEVEL = 10
              HAVING Count(*) > 1)
               Group By t1.SETTLEMENT_ID

)

select col1.SETTLEMENT_ID,col2.Total_HH_Memebers_Secondary, col1.Total_HH_Memebers_Primary from col1
join col2 on col1.SETTLEMENT_ID=col2.SETTLEMENT_ID

A: The error message is telling you that: A sub-query in the select list IS NOT ALLOWED TO return more than ONE VALUE, and this is true for EACH subquery.
You have 2 columns AND multiple rows returned from this query:

Select COUNT(t2.ID) as Total_HH_Memebers_Primary, t1.SETTLEMENT_ID
from PScData t1
INNER JOIN PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
WHERE  EXISTS (SELECT 1
               FROM   PScData t1
               WHERE  t1.SETTLEMENT_ID = SETTLEMENT_ID
                AND t2.EDUCATION_LEVEL = 5
               HAVING Count(*) > 1)
Group By t1.SETTLEMENT_ID

So IT IS NOT ALLOWED as a "subquery" inside a select clause.
You need to use "conditional aggregates" instead, explained elsewhere.

A: I have accepted the above answer and i have found another method for it as well:
Both methods are feasible,the method that i have found is given below:
WITH EDU_LEVEL AS
(SELECT t1.SETTLEMENT_ID,t2.EDUCATION_LEVEL from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
)

SELECT  SETTLEMENT_ID,
(Select COUNT(*) FROM EDU_LEVEL    WHERE  SETTLEMENT_ID = T.SETTLEMENT_ID AND EDUCATION_LEVEL = 5 ) Total_HH_Memebers_Primary,
(Select COUNT(*) FROM EDU_LEVEL    WHERE  SETTLEMENT_ID = T.SETTLEMENT_ID AND EDUCATION_LEVEL = 10 ) Total_HH_Memebers_Secondary

FROM EDU_LEVEL AS T
Group By SETTLEMENT_ID


text:
Q: JSON Object using Retrofit Kotlin I have data from api looking like that:
{
"id": 2015,
"area": {
    "id": 2081,
    "name": "France"
},
"name": "Ligue 1",
"code": "FL1",
"emblemUrl": null,
"plan": "TIER_ONE",
"currentSeason": {
    "id": 499,
    "startDate": "2019-08-09",
    "endDate": "2020-05-31",
    "currentMatchday": 21,
    "winner": null
},
"seasons": [
    {
        "id": 499,
        "startDate": "2019-08-09",
        "endDate": "2020-05-31",
        "currentMatchday": 21,
        "winner": null
    },
    {
        "id": 177,
        "startDate": "2018-08-10",
        "endDate": "2019-05-25",
        "currentMatchday": 38,
        "winner": null
    },
    {
        "id": 17,
        "startDate": "2017-08-04",
        "endDate": "2018-05-27",
        "currentMatchday": 38,
        "winner": {
            "id": 524,
            "name": "Paris Saint-Germain FC",
            "shortName": "PSG",
            "tla": "PSG",
            "crestUrl": "https://upload.wikimedia.org/wikipedia/en/a/a7/Paris_Saint-Germain_F.C..svg"
        }
    },
    {
        "id": 333,
        "startDate": "2016-08-12",
        "endDate": "2017-05-20",
        "currentMatchday": null,
        "winner": null
    },
    {
        "id": 334,
        "startDate": "2015-08-07",
        "endDate": "2016-05-14",
        "currentMatchday": null,
        "winner": null
    },
    {
        "id": 335,
        "startDate": "2014-08-08",
        "endDate": "2015-05-23",
        "currentMatchday": null,
        "winner": null
    },
    {
        "id": 336,
        "startDate": "2013-08-09",
        "endDate": "2014-05-17",
        "currentMatchday": null,
        "winner": null
    },
    {
        "id": 337,
        "startDate": "2012-08-10",
        "endDate": "2013-05-26",
        "currentMatchday": null,
        "winner": null
    },
    {
        "id": 338,
        "startDate": "2011-08-06",
        "endDate": "2012-05-20",
        "currentMatchday": null,
        "winner": null
    }
],
"lastUpdated": "2020-01-25T13:55:00Z"

}
And I try to get it in kotlin , but i dont know how to receive 'seasons' array.
Here is my kotlin class with data model
data class CompetitionModel(
@SerializedName("id")
val id: String?,
@SerializedName("area")
val area: AreaModel?,
@SerializedName("name")
val name: String?,
@SerializedName("code")
val code: String?,
@SerializedName("emblemUrl")
val emblemUrl: String?,
@SerializedName("plan")
val plan: String?,
@SerializedName("currentSeason")
val currentSeason: CurrentSeasonModel?,
@SerializedName("seasons")
val seasons: CurrentSeasonModel,
@SerializedName("lastUpdated")
val lastUpdated: String?

data class AreaModel(
@SerializedName("id")
val id: String = "",
@SerializedName("name")
val name: String = ""

data class CurrentSeasonModel(
@SerializedName("id")
val id: String = "",
@SerializedName("startDate")
val startDate: String = "",
@SerializedName("endDate")
val endDate: String = "",
@SerializedName("currentMatchday")
val currentMatchday: String = "",
@SerializedName("winner")
val winner: String = ""

class SeasonModel(
var seasons: CurrentSeasonModel

Because my SeasonModel (when i try to add []) outputs error:
"Parameters must have type annotation" - but i have my CurrentSeasonModel as my type - what am i doing wrong?

A: I assume you wanted to declare array of CurrentSeasonModel. In Kotlin you would declare it as Array<CurrentSeasonModel>, but in your use case I would recommend using List<CurrentSeasonModel>.


text:
Q: About a limit-no l'hospital or derivatives So i've come across this limit:
$\lim_{x\to1} x^{\cot{\pi x}}$
So i found that its possible to solve without using those before-mentioned tools.
I'm not sure how to do this limit,while i get stuck at this:
$\lim_{x\to 1} x^{\frac{\cos{\pi x} { \pi x}}{sin{\pi x}{  \pi x}}}$
I know i have to change the variable,so that i will $\lim_{t\to\infty}....$ for the modified variable $t$,  but i am stuck at that part.
Thank you in advance. Any help would be appreciated.

A: Take $t=1-x$ and rewrite the expression as $ \exp( \cot(\pi (1-t)) \log (1-t) )$. The cosine just tends to $-1$, so it all amounts to evaluating $$ \lim_{t\to 0} \exp \left( - \frac{\log (1-t) }{\sin (\pi (1-t) )} \right) =  \lim_{t\to 0} \exp \left( - \frac{\log (1-t) }{t} \frac{\sin t}{\sin (\pi (1-t) )} \right) = e^{1/\pi}, $$ where we have used two elementary limits.

A: Apply $\ln$ to get
$$\tag 1\cot \pi x \ln x = \cos \pi x \frac{\ln x}{\sin \pi x}= \cos \pi x \frac{(\ln x-\ln 1)/(x-1)}{(\sin \pi x-\sin \pi\cdot 1)/(x-1)}.$$
As $x\to 1,\cos \pi x \to -1.$ In the fraction, use the definition of the derivative to see the top $\to \ln'(1) = 1,$ the bottom $\to$ the derivative of $\sin \pi x$ at $1,$ which is $\pi \cos \pi = - \pi.$ The limit of $(1)$ is thus $1/\pi.$ Exponentiating back gives $e^{1/\pi}$ for the original limit. (Note that the restriction $x\to 1^-$ is not needed. The full limit as $x\to 1$ is $e^{1/\pi}.$)
OK, I used the definition of the derivative and two basic derivative results. Are these not permitted here?


text:
Q: ExecuteReaderAsync does not throw exception when Result Set and Exception both return by Stored Procedure I have a Stored Procedure which sometimes return an exception after SELECT statement.
For example:
BEGIN TRY
 SELECT
    EmployeeId,
    EmployeeName
 FROM dbo.abc

 THROW 50000, 'exception occurs here', 16;
END TRY
BEGIN CATCH
 THROW 50000, 'exception', 16;
END CATCH

I am using ExecuteReaderAsync method to read data.
In case of exception, I should get exception in application. For example:
using (var reader = await ExecuteReaderAsync())
{
 while (reader.Read())
 {
 }
}

But I am not getting any exception.
This is a very strange behaviour.
Because if this happens when we have some logic after SELECT and logic fails (e.g. any important UPDATE statement fails) then this will cause problem in the Application's behaviour.
Can somebody help me why I this strange behaviour is happening.

A: It is possible that this is simply because you disposed the reader before it had found the error - which is later in the stream than the first grid. Try doing:
using (var reader = await ExecuteReaderAsync())
{
    while (reader.Read()) { ... }

    // consume any trailing pieces
    while (reader.NextResult()) {}
}

The second loop (over NextResult()) ensures that the TDS parser has consumed the entire result. You might also prefer to use await reader.ReadAsync() and await reader.NextResultAsync(), since you're clearly in an async method here.

A: I encountered this in an additional scenario using the following code:
using (DbDataReader reader = await command.ExecuteReaderAsync(CommandBehaviour.SingleResult).ConfigureAwait(false))
{
    // ...

    while (await reader.NextResultAsync().ConfigureAwait(false)) { }
}

In this scenario, CommandBehaviour.SingleResult will prevent the exception being raised when a result set is returned first, even when using the NextResult loop. It will stop reading from the connection once it receives a result which means it doesn't see the error.
To fix, just remove the CommandBehaviour parameter from ExecuteReaderAsync() and ensure you include the while loop.


text:
Q: Python how to generate additional values between two row-values in a dataframe I have a data frame of two float columns. I want to create additional float values in between the row-values. Incidentally, I want to stack the generated values into new rows between them. I have two methods do it.
df =
       data1    data2
0      1.913  8.284000
1     13.060  8.261000
2     24.041  8.252000

I want to generate 5 additional rows between rows in above dataframe. I would like to achieve it in two methods.
Method1: expected output is given below. In this, addtional values are created in data1 column as np.linspace(1.913,13.060,7) as given below from index 0 to 6. The data2 column maintains a constant value 8.284 in these additional rows.
newdf1 =
       data1           data2
0      1.913          8.284000   ## Original row
1      3.77083333     8.284000   ## Generated row
2      5.62866667     8.284000   ## Generated row
3      7.4865         8.284000   ## Generated row
4      9.34433333     8.284000   ## Generated row
5      11.20216667    8.284000   ## Generated row
6      13.060         8.261000   ## Original
7                     8.261000
.                     8.261000
.
                      8.261000
12     24.041        8.252000

Method2: expected output is given below. The data1 column follows same approach as in above Method1. Now, data2 column values are also mapped. Ex, np.linspace(8.284000,8.261000,7)
newdf2 =
       data1           data2
0      1.913          8.284000     ## Original row
1      3.77083333     8.28016667   ## Generated row
2      5.62866667     8.27633333   ## Generated row
3      7.4865         8.2725       ## Generated row
4      9.34433333     8.26866667   ## Generated row
5      11.20216667    8.26483333   ## Generated row
6      13.060         8.261000     ## Original
7
.

12     24.041        8.252000

A: I suggest splitting your task in two parts:

*

*Inserting (empty) extra rows to the DataFrame

*Filling those extra rows according to your given rules (interpolation).

For the first part, a (admittedly complex) list comprehension will do. For the second part, the pandas DataFrame's method .interpolate() is your friend.
But let's not get ahead of ourselves. We first generate your original DataFrame:
df = pd.DataFrame({'data1': [1.913, 13.060, 24.041], 'data2': [8.284, 8.261, 8.252]})

1. Inserting extra rows between existing values
Now we generate a dict containing the original data, as well extra values in between (NaNs). We then create a new DataFrame from the dict:
line_ins = 5 # Number of lines to insert
res_dict = {col: [y for val in df[col] for y in [val] + [np.nan]*line_ins][:-line_ins] for col in df.columns}
df_new = pd.DataFrame(res_dict)

Explanation of list comprehension: for each value (val) in the DataFrame's column, we also add five np.nan's ([val] + [np.nan]*line_ins).
In the end we cut of the last five values from the generated list ([:-line_ins]), because we don't want to have the additional rows after the last value. Finally, we flatten the list (hence the stacked list comprehension).
2. Determining values of new rows (interpolation)
Method 1
In this case we want to linearly interpolate the column data1, while for data2 we want to use the existing values:
df_new['data1'] = df_new['data1'].interpolate()
df_new['data2'] = df_new['data2'].interpolate(method='pad')

The resulting df_new contains the following:
        data1  data2
0    1.913000  8.284
1    3.770833  8.284
2    5.628667  8.284
3    7.486500  8.284
4    9.344333  8.284
5   11.202167  8.284
6   13.060000  8.261
7   14.890167  8.261
8   16.720333  8.261
9   18.550500  8.261
10  20.380667  8.261
11  22.210833  8.261
12  24.041000  8.252

Method 2
In this case we want to linearly interpolate both columns, making things even easier:
df_new = df_new.interpolate()

And the contents of the resulting df_new:
        data1     data2
0    1.913000  8.284000
1    3.770833  8.280167
2    5.628667  8.276333
3    7.486500  8.272500
4    9.344333  8.268667
5   11.202167  8.264833
6   13.060000  8.261000
7   14.890167  8.259500
8   16.720333  8.258000
9   18.550500  8.256500
10  20.380667  8.255000
11  22.210833  8.253500
12  24.041000  8.252000


text:
Q: Numpy LinAlg quandary: is there a trick to using np.linalg.inv? In the code pasted below, I have two arrays (matrices) - a,b - where 'b' is the inverse of 'a'. A dot product therefore should, an initially does give us 'I', the identify matrix. All good until I use np.linalg.inv to get 'b1`, which btw looks like 'b', but the dot product gives a way diff answer in 'I1'.
What gives? And yes, this is a non-zero det and all that. It's a simple example but I'm missing something like how to address floating points or something else.
import numpy as np

    a = np.array([[0,1,2], [1,2,3], [3,1,1]])
    b = np.array([[1/2,-1/2,1/2], [-4,3,-1],[5/2,-3/2,1/2]])

    I = np.dot(a,b)
    I
    ###
    array([[1., 0., 0.],
           [0., 1., 0.],
           [0., 0., 1.]])
    ###

    #vs
    b1 = np.linalg.inv(a)
    I1 = np.dot(a,b1)
    I1
    ###
    array([[1.00000000e+00, 0.00000000e+00, 1.11022302e-16],
           [8.88178420e-16, 1.00000000e+00, 2.22044605e-16],
           [0.00000000e+00, 0.00000000e+00, 1.00000000e+00]])
    ###