text:
Q: File upload with postman works but fails with Apache HttpClient Problem
I'm working with an external REST API on a test system. There is an upload path I'm trying to implement and I am using the Apache HTTPClient. I tried it with the following postman configuration and it works perfectly:

The upload works fine like that.
Implementation in Java
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPut request = new HttpPut("../upload") // placeholder url, not the real one

request.setHeader("Content-type", "multipart/form-data");
request.setHeader(HttpHeaders.AUTHORIZATION, "HEY I AM A TOKEN");

FileBody fileBody = new FileBody(new File("dummy.pdf"), ContentType.create("application/pdf"));
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart("file", fileBody);
request.setEntity(builder.build());

CloseableHttpResponse response = httpClient.execute(request);

Error
I always get a specific error from the rest api:
File could not have been parsed

The documentation of the upload path mentions the following details:

*

*Header Content-Type multipart/form-data

*Only one multipart element

*Content-Type of the element needs to be application/pdf

*Name needs to be "file"

I think I do every point of this list in my request - so what is the difference between the postman request and my own java http request?
What do I miss?
EDIT:
The same code with OkHTTP works. Still don't know why it does not work with Apache HttpClient.
OkHttpClient testClient = new OkHttpClient();
File testfile = new File("dummy.pdf");

RequestBody body = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("file","dummy.pdf",
RequestBody.create(MediaType.parse("application/pdf"),testfile)).build();

Request testreq = new Request.Builder()
.url("../upload")
.header("Authorization", "HI I AM A TOKEN")
.put(body)
.build();
Response testres = testClient.newCall(testreq).execute();

A: I had to remove this line
request.setHeader("Content-type", "multipart/form-data");

to make it work. I dont really know why so if someone can help me out with this and give some explanation I'm up for it. For the moment I'm happy because it works now.


text:
Q: pl/sql save as hi im from madrid and i wanted to know how to save a query/cursor, in a XXXXXXX.sql.
thanks!!!

A: well, Toad has a save as function.
Run your query, right=click in the datagrid and choose Save As.  You'll get a screen of options.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I read a header from an http request in golang? If I receive a request of type http.Request, how can I read the value of a specific header? In this case I want to pull the value of a jwt token out of the request header.

A: Note: The accepted answer is missing some information.
A Header represents the key-value pairs in an HTTP header.
It's defined as a map where key is of string type and value is an array of string type.
type Header map[string][]string

Actually, r.Header.Get gets the first value associated with the given key i.e. it just gets the first string from index 0.
This is okay if your header just have one value but if it has multiple values, you may miss out on some information.
Eg. User-Agent header has multiple values against the same key.
user-agent: ["Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6)",  "AppleWebKit/537.36 (KHTML, like Gecko)", "Chrome/80.0.3987.106 Safari/537.36",]

So if you use r.Header.get("User-Agent") , it'll return Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) only and not the rest of the values.
If you want to get all the values you can use this:
req.Header["User-Agent"]

A: package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/", handler)
    log.Fatal(http.ListenAndServe("localhost:8000", nil))
}

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "%s %s %s \n", r.Method, r.URL, r.Proto)
    //Iterate over all header fields
    for k, v := range r.Header {
        fmt.Fprintf(w, "Header field %q, Value %q\n", k, v)
    }

    fmt.Fprintf(w, "Host = %q\n", r.Host)
    fmt.Fprintf(w, "RemoteAddr= %q\n", r.RemoteAddr)
    //Get value for a specified token
    fmt.Fprintf(w, "\n\nFinding value of \"Accept\" %q", r.Header["Accept"])
}

Connecting to http://localhost:8000/ from a browser will print the output in the browser.

A: You can use the r.Header.Get:
func yourHandler(w http.ResponseWriter, r *http.Request) {
    ua := r.Header.Get("User-Agent")
    ...
}


text:
Q: Using rsync through intermediate host with `sudo` on jump-host I am user1@host1 and would like to transfer data via rsync from user3@host3. However, I can access host3 only via user3@host2. The catch is, that I can become user3 on host2 only via su or sudo, but have to connect to host2 as user2.
So in order to login to host3 on the shell I execute:
user1@host1 $ ssh user2@host2
user2@host2 $ su user3
user3@host2 $ ssh host3
user3@host3 $ # done!

My attempts to encapsulate all this in a (single) call to rsync lead to the following:
rsync -a -e "ssh -A user2@host2 'sudo -u user3 ssh'" host3:/... /...

Unfortunately, requiretty is set in /etc/sudoers on host2, so this results in the message: sudo: sorry, you must have a tty to run sudo.
I can add -tt to the ssh call:
rsync -a -e "ssh -tt -A user2@host2 'sudo -u user3 ssh'" host3:/... /...

In which case I get: protocol version mismatch -- is your shell clean?. Apparently, there is some output on host2's TTY that causes rsync to fail. I have no control over either that output or /etc/sudoers.
Is there any way I can do this, maybe using ProxyCommand or SSH tunnels?

Using this simplescript.sh it works:
#!/bin/sh
ssh user2@host2 "su user3 -p -c 'ssh $@'"

Then with rsync:
rsync -av -e './simplescript.sh' pmtlnx009.wob.vw.vwg:/tmp/t19 /tmp/t19

That is fine, I guess; it would be nice, though, to integrate the script into the CLI call.


text:
Q: hello, this is my first experience with mui, I can't export normally import { DehazeIcon} from "@mui/icons-material"; gives error ( this is my first experience with mui, I can't export normally import { DehazeIcon} from "@mui/icons-material"; gives error (
my package.json
{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@emotion/react": "^11.10.0",
    "@emotion/styled": "^11.10.0",
    "@mui/icons-material": "^5.8.4",
    "@mui/lab": "^5.0.0-alpha.93",
    "@mui/material": "^5.9.3",
    "@mui/styled-engine-sc": "^5.9.3",
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.3.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.3.0",
    "react-scripts": "5.0.1",
    "styled-components": "^5.3.5",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "autoprefixer": "^10.4.8",
    "postcss": "^8.4.14",
    "tailwindcss": "^3.1.7"
  }
}

enter code here
and my Header.js
    import React from "react";
    import { Link } from "react-router-dom";
    import { DehazeIcon} from "@mui/icons-material";

    //.....

          <DehazeIcon/>

      );
    };

export default Header;

enter code here
and error:
enter code here
enter image description here
I can't understand what the error is, 4 mui doesn't suit me, I don't want to react to version 17 either

A: You're using the wrong name, MUI icons don't have the Icon suffix. You can find a full list of the icons here
Instead, import like this:
import { Dehaze } from @mui/icons-material

Or you can change the name its refered to by importing like this:
import { Dehaze as DehazeIcon } from @mui/icons-material

You can also import from the default export of the individual module, like Enfield li added in a comment. See the usage guid here


text:
Q: I'm trying to copy one text file to another using c I'm trying to copy one test file to another in C. However my code is not working the program runs fine and produces a file CircleCode_temp but there is nothing in the text file. Any ideas why its not working
   #include <stdio.h>
   #include <stdlib.h>

   char c;

  int main(int argc, char **argv)
  {

  FILE *orginalFile = fopen("CircleCode1", "r");
  FILE *newFile = fopen("CircleCode_temp", "w");

    if (orginalFile == NULL | newFile == NULL)
     {
       printf("Cannot open file");
       exit(0);
     }

      while((c = fgetc(orginalFile))!=EOF)
      {
         fputc(c,newFile);
         c = fgetc(orginalFile);
       }

      fclose(orginalFile);
      fclose(newFile);

     return 0;
   }

A:   while((c = fgetc(orginalFile))!=EOF)
  {
     fputc(c,newFile);
     c = fgetc(orginalFile);
   }

Two mistakes here:

*

*You call fgetc twice in the loop, which throws every other character away.

*You compare c to EOF. You're suppose to compare the return value of fgetc to EOF. If you think they're the same, remember that c is of type char and fgetc returns an int.
Also:
    if (orginalFile == NULL | newFile == NULL)

One mistake here. You have | which is bitwise OR, but you want ||, which is a logical OR.


text:
Q: javascript convert character to key code
Possible Duplicate:
Convert character to ASCII code in Javascript

How can I convert any character to the key code  like
m    77
n    78
o    79
p    80
q    81
r    82
s    83
t    84
u    85
v    86

A: var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split(''),
    len = alphabet.length,
    i;

for (i = 0; i < len; ++i) {
    console.log(alphabet[i], alphabet[i].charCodeAt(0) - 32);
}

http://jsfiddle.net/zerkms/n2ZFa/


text:
Q: Can serial voting detection be bypassed?
I know there should be a script running and probably I'll get my rep back eventually, but I can't help taking this personally. I mean... WTH? This seems like a petty act. Moreover, I'm going for the Legendary badge, and if I get my rep back on a different day, that's not really helpful.
Who, other than scripts, looks into this? Will the person responsible for this be dealt with in any way?
Is there no way to keep serial downvoting at bay?
Sorry for the duplicate, it's just really REALLY frustrating...
EDIT: Some new info
This started 3 days ago. The rep was restored (although not for the same day, so there's a minus there) for the first day. However, yesterday and today it continued. Not as many downvotes, but clearly someone's going out of their way to downvote me. Also, the rep lost yesterday wasn't recovered. Could someone have figured out how to bypass the scripts?

As you can see, more recently the votes are some time apart. I only highlighted those that are on old questions. Agreed, you might stumble into an old question and downvote it, but to me this seems like much more than a coincidence.

A: A user was trying to stay "under the radar" with respect to downvoting you (several checks are in place, he was doing it at a very low volume as to avoid all of them).  We have invalidated all involved votes.
The offender has been dealt with.  If, after their vacation, they offer an encore...let's just say they don't want to do that...


text:
Q: How to estabilish a secure connection on localhost with angular dart webdev? I'm using angular dart to build a web application, and when it comes to accessing user location feature such as geolocation, browsers like chrome enforce https.
When I deploy the web application the location api works because the connection is secure, but when I debug on localhost it is broken because (I assume) of the unsecure session.
Is there a way to configure the webdev generated http server to use somehow a self signed ssl certificate?
Is there any viable alternative?

A: Yes, --tls-cert-chain and --tls-cert-key flags were just added to webdev serve. I used this tutorial for setting up the cert and key: https://www.freecodecamp.org/news/how-to-get-https-working-on-your-local-development-environment-in-5-minutes-7af615770eec/.
Then the following command served up the app at https://127.0.0.1:8080
webdev serve --release --tls-cert-chain path-to-cert/server.crt --tls-cert-key path-to-key/server.key
The changes are in webdev 2.5.0.


text:
Q: Is there any way to trigger component method from parent in VueJS? I have been searching for information and have only found a way to emit events from child components which can be then listened for in parent components. Is there any way to call a child method from parent component?

A: I think a good pattern for this is emitting an event from the parent component and listening to it in the child component, using an Event Bus.
That would be:
in main.js
export const bus = new Vue()

in Parent.vue:
import {bus} from 'path/to/main'

// Where you wanna call the child's method:
bus.$emit('customEventName', optionalParameter)

in Child.vue:
import {bus} from 'path/to/main'

// Add this to the mounted() method in your component options object:
bus.$on('customEventName', this.methodYouWannaCall)

A: Yup, just find your component in children array, or grab it by ref attribute, and call method :)
ref doc
lets assume that your child component has method x.
According to documentation:
<div id="parent">
  <user-profile ref="profile"></user-profile>
</div>

var child = this.$refs.profile;
child.x();


text:
Q: how to check the textarea content is blank using javascript? using value.length != 0 ..doesn't work for the blank space situation

A: Try this:
if (value.match (/\S/)) { ... }

It will make sure value has at least 1 non-whitespace character

A: document.myForm.myField.value != ""; // or
document.myForm.myField.value.length == 0;

Example:
function isEmpty() {
  alert(document.myForm.myField.value == "");
}

--
<button onclick="isEmpty()">Is Empty?</button>
<form name="myForm">
  <input type="text" name="myField" />
</form>

A: Try jquery and use its trim() feature. If someone is inputting spaces, value will be neither null nor length == 0.

A: Since you clearly already know how to get the value, I'll skip that bit.
var value; // we'll assume it's defined
if(value) {
    // textarea content is not empty
} else {
    // textarea content is empty
}

'' evaluates to false. Seems simple enough. What blank space situation are you talking about?


text:
Q: Rewrite integral in terms of Bessel functions Trying to rewrite this integral:
$$\int dq \frac{q^2}{2\pi^2} \frac{\sin(\sqrt{q^2+m^2}t)}{\sqrt{q^2+m^2}} \frac{\sin (qr)}{qr}$$
In terms of the Bessel function of the first kind, $J_0$ but have no idea how to since I'm not used to Bessel functions.
I know that the answer should be:
$$\frac{1}{4\pi r} \frac{\partial}{\partial r} J_0(m\sqrt{t^2-r^2}) r>0$$

A: Hint:
Let $q=m\sinh u$ ,
Then $dq=m\cosh u$
$\therefore\int\dfrac{q^2}{2\pi^2}\dfrac{\sin(\sqrt{q^2+m^2}t)}{\sqrt{q^2+m^2}}\dfrac{\sin (qr)}{qr}~dq$
$=\int\dfrac{m^2\sinh^2u}{2\pi^2}\dfrac{\sin\left(t\sqrt{m^2\sinh^2u+m^2}\right)}{\sqrt{m^2\sinh^2u+m^2}}\dfrac{\sin(rm\sinh u)}{rm\sinh u}~d(m\sinh u)$
$=\dfrac{m}{2\pi^2r}\int\sin(mr\sinh u)\sin(mt\cosh u)\sinh u~du$
$=\dfrac{m}{4\pi^2r}\int\cos(mr\sinh u-mt\cosh u)\sinh u~du-\dfrac{m}{4\pi^2r}\int\cos(mr\sinh u+mt\cosh u)\sinh u~du$
$=\dfrac{m}{8\pi^2r}\int e^u\cos\left(\dfrac{m(r-t)e^u}{2}-\dfrac{m(r+t)}{2e^u}\right)~du-\dfrac{m}{8\pi^2r}\int e^{-u}\cos\left(\dfrac{m(r-t)e^u}{2}-\dfrac{m(r+t)}{2e^u}\right)~du-\dfrac{m}{8\pi^2r}\int e^u\cos\left(\dfrac{m(r+t)e^u}{2}-\dfrac{m(r-t)}{2e^u}\right)~du+\dfrac{m}{8\pi^2r}\int e^{-u}\cos\left(\dfrac{m(r+t)e^u}{2}-\dfrac{m(r-t)}{2e^u}\right)~du$

A: Hint: One possible start that is a bit too long for a comment could be to start with definition for Bessel function according to wikipedia:
$$x^2\frac{\partial^2 y}{\partial x^2} + x\frac{\partial y}{\partial x}+(x^2-\alpha^2)y = 0$$
Subtract last term from both sides:
$$x^2\frac{\partial^2 y}{\partial x^2} + x\frac{\partial y}{\partial x} =
 -(x^2-\alpha^2)y$$
Assume $(x^2-\alpha) \neq 0$ and divide on both sides:
$$\frac{x^2}{x^2-\alpha^2}\frac{\partial^2 y}{\partial x^2} + \frac{x}{x^2-\alpha^2}\frac{\partial y}{\partial x} =
 -y$$
Maybe you can continue from there?


text:
Q: Verificar o input e então clicar no button Como que eu faço para somente se o input estiver marcado é que a pessoa pode clicar no "ok,entendi".

    <button type="button" class="btn btn-info" (click)="openModal(template)">Create template modal</button>

    <ng-template #template>

Termo

            <button type="button" class="close pull-right" aria-label="Close" (click)="modalRef.hide()">
         ×
       </button>

Lorem Ipsum is simply dummy text of the printing and typesetting industry.
             Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
             when an unknown printer took a galley of type and scrambled it to make a type

            <input class="input_box" name="checkbox" type="checkbox" value="termo" />
            Li e aceito os termos e condições acima.

            <button type="button" class="btn btn-warning btn-lg btn-block">ok,entendi</button>

    </ng-template>

A: Utilize os eventos e atributos.
no seu input você faz assim:
<input type="checkbox" [checked]="termo" (change)="termo= !termo">

no seu componente:
// você cria a variável e atribui false
termo: boolean = false;

no seu botão:
<button type="submit" [disabled]="!termo">ok,entendi</button>


text:
Q: How to get database table header information into an CSV File I am trying to connect to the database and get current state of a table and update that information into csv file, with below mentioned piece of code, am able to get data information into csv file but am not able to get header information from database table into csv file.
So my questions is How can I get Database Table Header information into an CSV File ?
$config['database'] = 'sakila';
$config['host'] = 'localhost';
$config['username'] = 'root';
$config['password'] = '';

$d = new PDO('mysql:dbname='.$config['database'].';host='.$config['host'], $config['username'], $config['password']);
$query = "SELECT * FROM actor";
$stmt = $d->prepare($query);

// Execute the statement
$stmt->execute();

var_dump($stmt->fetch(PDO::FETCH_ASSOC));

$data = fopen('file.csv', 'w');

while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
    echo "Hi";
    // Export every row to a file
    fputcsv($data, $row);
}

Header information meaning:
Vehicle     Build   Model
 car        2009    Toyota
 jeep       2007    Mahindra

So header information for this would be Vehicle Build Model
Any guidance would be highly appreciated.

A: Using SHOW COLUMNS FROM  will get you the column names from . You then can write the first line of your CSV with them:
// Do this before adding the rows from the database
$query = "SHOW COLUMNS FROM some_table";
$stmt = $d->prepare($query);
$stmt->execute();
$columns = '';
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
    $columns .= $row['Field'] . ',';
}
$columns = substr($columns, 0, -1);
fputcsv($data, $columns);

A: Just get the keys from the array $row: array_keys(). Now you have all the columnnames and you can put them in your csv-file.
======= EDIT =======
<?php

$header = array();

while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
    if(empty($header)){ // do it only once!
      $header = array_keys($row); // get the columnnames
      fputcsv($data, $header); // put them in csv
    }

    echo "Hi";
    // Export every row to a file
    fputcsv($data, $row);
}
?>

A: Use mysqldump:
mysqldump -u user -p --fields-terminated-by=',' --tab=/tmp mydatabase mytable

The above command will create 2 files in /tmp. mytable.sql and mytable.txt. The sql file will contain the table creation schema and the txt file will contain the records of the mytable table with fields delimited by a comma.

A: You already have it in PDO::FETCH_ASSOC: returns an array indexed by column name as returned in your result set
EDIT:
One way to get and write the names of columns is (put it before your while lopp)
fputcsv($data, array_keys($stmt->fetch(PDO::FETCH_ASSOC)));

Read about php arrays and associative arrays in particular and on function on arrays (such as array_keys). Answers to particular questions can not replace understanding of basic concepts such as arrays.


text:
Q: Undefined methods in the extended class I have this code and I am extending a class but it says the method is undefined.
<?php
class api{
    //$api_Key;
    public function getURL($url){
        return file_get_contents($url);
    }
    public function postURL($url){
        $ch = curl_init( $url );
        curl_setopt( $ch, CURLOPT_POST, 1);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec( $ch );
        curl_close($ch);
        return $response;
    }
    public function getJSON($json){
        return json_decode($json);
    }
}
class geo extends api{
    public function getLocation(){
        return json_decode(postURL("https://www.googleapis.com/geolocation/v1/geolocate?key=$key"));
    }
}
class vote extends geo {
// Class properties and methods go here
}

?>

PHP file to view on web
<?php
        include("php/vote.php");
            $geo = new geo();
             echo $geo->getLocation();
        ?>

I am getting this error Fatal error:

Call to undefined method geo::json_decode() in
  G:\wamp\www\voting\php\vote.php on line 22

I have yet to find something that would help me solve this I have the parent and child classes right or I think I do.
It is extending the class so I am not sure why it is undefined any help would be awesome.

A: json_decode() is a built-in PHP function not a method of either of your classes.  You also forgot the $this reference for your method postURL(). Remove $this from json_decode() and use $this->postURL:
return json_decode($this->postURL("https://www.googleapis.com/geolocation/v1/geolocate?key=$key"));

But I assume you actually want to use your method getJSON():
return $this->getJSON($this->postURL("https://www.googleapis.com/geolocation/v1/geolocate?key=$key"));


text:
Q: How to check if a user exists by a given id Is there any way to check if a user id exists? I want to create a function similar to username_exists() but which returns if the id exists or not.

A: In this case I will definetely not use the get_userdata( $user_id ) while it is returning a WP_User, so it is more greedy than just a custom query.
About the query, I agree using the prepare method, but the SELECT COUNT(*) means you are returning all columns, which is useless here.
I would recommend using SELECT COUNT(ID) unstead, in this way we are only working on a single column which will be faster.
On other aspect for the returning statement, it would be more readable with a Ternary Logic like : return 1 < $count ? true : false;
To sum up, I wouldd have implemented it like :
function user_id_exists( $user_id ) {
    global $wpdb;
    $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(ID) FROM $wpdb->users WHERE ID = %d", $user_id ) );
    return empty( $count ) || 1 > $count ? false : true;
}

A: I would highly recommend Daniel's much simpler solution over the one currently selected as correct:
$user = get_userdata( $user_id );
if ( $user === false ) {
    //user id does not exist
} else {
    //user id exists
}

A: If performance is a concern, use:
function user_id_exists($user_id) {
    global $wpdb;

    // Check cache:
    if (wp_cache_get($user_id, 'users')) return true;

    // Check database:
    if ($wpdb->get_var($wpdb->prepare("SELECT EXISTS (SELECT 1 FROM $wpdb->users WHERE ID = %d)", $user_id))) return true;

    return false;
}

Otherwise, use get_userdata($user_id) !== false. The call to get_userdata will retrieve a whole row from the database instead of a single value, create a new WP_User object and cache it on success.

A: Use this function:
function user_id_exists($user){

    global $wpdb;

    $count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $wpdb->users WHERE ID = %d", $user));

    if($count == 1){ return true; }else{ return false; }

}

Usage:
if(user_id_exists(1)){
    //it does exists
} else {
    //it doesn't
}

A: Something that is done by at least a few hackers ( I know because I played victim to this at least once) is to visit your site using this type of URL
domain.com/?author=0

domain.com/?author=1

etc.
On a successful attempt the output of the site will have valid data, in addition the user nicename will be in the content of the website and the nickname may be there as well (depending on the pages output).
On an invalid attempt the site will go to the 404 page (or whatever is set to happen on a page not found error).
It can be rather trivial to build a script using cURL that can test from say author=0 up to author=999 in a relatively short amount of time and output a list of usernames. I had a hacker do this for one of my sites and then try to login to each user by using another list of popular passwords.
As you can imagine the first time this happens it is a bit scary to see that someone can quite easily find out all your usernames. Lucky for me strong passwords saved the day that time, I'm sure not everyone is so lucky.
I have tested this against a couple big name websites (who will remain nameless in this post) and it seems that there may be nothing anyone can do as of yet to stop this from happening. I personally think it is security risk that wordpress should close.
EDIT:
Here in the future (early 2016) I now know that there are methods/plugins which can thwart this user enumeration attack. And I further have changed my stance on the security risk of this and I no longer think WordPress should change this.

A: Try This will not Showing you the warning like Missing argument 2 for wpdb::prepare()
function user_id_exists($user_id){
    global $wpdb;
    $count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $wpdb->users WHERE ID = %d",$user_id));
    if($count == 1){ return true; }else{ return false; }
}


text:
Q: CROSS APPLY function in Presto/AWS I'm trying to convert 4 date columns titled Created, Approved, Processed & Realized to a single column with all 4 dates AND a second column with the status of each of those dates.
The image at the end shows the data issue visually (apologies I'm still figuring out how to attach tables in textual form on stackoverflow)

To solve this, I successfully executed the CROSS APPLY
function in SQL server (see below), but I now need to do the same in AWS Simba
Athena or the Presto language. Can someone please guide me on what is the AWS/Presto equivalent of a CROSS APPLY function? Thank you in advance

SELECT

    V.Date,
    V.Status
    From Table C
    CROSS APPLY
        (VALUES
                (C.Created, 'Opened'),
                (C.Approved, 'Approved'),
                (C.Processed, 'Processed'),
                (C.Realized, 'Realized')
                                                 ) AS V([Date], Status)

I want to convert the following table:

A: You should be able to use UNNEST for this:
SELECT v.date, v.status
FROM m_table
CROSS JOIN UNNEST(ARRAY[
 ROW(C.Created, 'Opened'),
 ROW(C.Approved, 'Approved'),
 ROW(C.Processed, 'Processed'),
 ROW(C.Realized, 'Realized')
]) AS v(date, status);

This works in the latest Presto version, 337.
In Athena you probably still cannot UNNEST array or ROW
in ANSI SQL manner, so you may need some modifications.


text:
Q: Fetching messege from layerkit ios error I am creating a group through layer kit iOS SDK. Owner of group is sending push to participants and one message while creating a group. Problem is that when participants fetch the message the conversation object comes null some times, below is my code
query = [LYRQuery queryWithQueryableClass:[LYRConversation class]];
 query.predicate = [LYRPredicate predicateWithProperty:@"identifier" predicateOperator:LYRPredicateOperatorIsEqualTo value:eventDetail[@"layerConversation"]];
NSError *error = nil;
conversation = [[self.layerClient executeQuery:query error:&error] firstObject];

NSLog(@"%@?????????????????? and layer client  %@",conversation, self.layerClient );


text:
Q: Let $K⊆M⊆L$, such that $[L:K]=n$ for some $n∈\mathbb{N}$. Prove $[M:K]$ is well-defined. I wanted to delve into Galois theory as soon as possible, so I started reading a book on the topic without previous knowledge of other areas of mathematics which are often needed to understand Galois. Because of this I do not understand the usual definition of a field extension (which makes use of the concept of a Vector Space), but rather employ a different (I believe equivalent) definition:
Let $L, K$ be subfields of $\mathbb{C}$ such that $K⊆L$
Let $A = $ {$x_1, ..., x_n$} $⊆L$ be a set of linearly independent elements over $K$ such that $L = $ {$x_1k_1+...+x_nk_n|k_i∈K$}, then $[L:K]=n$. We call $A$ a basis for $L:K$.
From such definition, is it possible to prove that if $K⊆M⊆L$, such that $[L:K]=n$ for some $n∈\mathbb{N}$ then $[M:K]$ is well defined. In other words, that there exists a set $B⊆M$  which is a basis for $M:K$.
I'm aware my definition only speaks of finite field extensions.
I would really appreciate any help/thoughts.


text:
Q: __proto__ doesn't seem to work after a null assignment - bug or feature? I have observed a behaviour regarding __proto__ which seems weird to me: when changing __proto__ to various objects it behaves as expected, but once it is set to null changing it again to another object doesn't seem to have an effect.
Is this a bug in the implementation, or the desired behaviour? If this is the desired behaviour, can someone shed a light as to why?
An example JavaScript code (all the tests pass fine until the last line):
p = {
  sum: function() {
    return this.x + this.y;
  }
};

o = {
  x: 1,
  y: 2
};

o.sum(); // As expected: TypeError: o.sum is not a function

// These all behave as expected:
o.__proto__ = p;
o.__proto__; // [object Object]
o.__proto__.sum; // [object Function]
o.sum(); // returns 3 :-)

// These all behave as expected:
o.__proto__ = {};
o.__proto__; // [object Object]
o.sum(); // TypeError: o.sum is not a function

// These all behave as expected:
o.__proto__ = p;
o.__proto__; // [object Object]
o.__proto__.sum; // [object Function]
o.sum(); // returns 3 :-)

// Still behaves more or less as expected:
o.__proto__ = null;
o.__proto__; // undefined (why undefined and not null?)
o.sum(); // TypeError: o.sum is not a function

// Seems fine, until the last line:
o.__proto__ = p;
o.__proto__; // [object Object]
o.__proto__.sum; // [object Function]
o.sum(); // Expected 3, but... TypeError: o.sum is not a function

I'm working with Firefox 28.0; don't know how other browsers react.

A: The issue is that __proto__ in Firefox is an actual property on Object.prototype implemented with getter/setter functions. So when you set the __proto__ of o to null, you wiped out the entire prototype chain, which included the __proto__ property.
Now when you assign to __proto__, you're just assigning a new, normal property that doesn't have the desired behavior directly to the o object.

So in order to get the functionality of __proto__, you'll need to go to Object.prototype, and borrow the .set method of the __proto__ property, and use .call to allow it to operate on the o object.
Object.getOwnPropertyDescriptor(Object.prototype, "__proto__").set.call(o, p);

So this invokes the set function of Object.prototype.__proto__ using .call so that the o becomes the this value of set, and p is the value being set. This will make __proto__ operate on o as though it was a property of o, allowing it to set the internal [[Prototype]] property.

Note that this is only tested in Firefox.


text:
Q: Create a new cluster in Databricks using databricks-cli I'm trying to create a new cluster in Databricks on Azure using databricks-cli.
I'm using the following command:
databricks clusters create --json '{ "cluster_name": "template2", "spark_version": "4.1.x-scala2.11" }'

And getting back this error:
Error: {"error_code":"INVALID_PARAMETER_VALUE","message":"Missing required field: size"}

I can't find documentation on this issue, would be happy to receive some help.

A: Just to add to the answer that @MorShemesh gave, you can also use a path to a JSON file instead of specifying the JSON at the command line.
databricks clusters create --json-file /path/to/my/cluster_config.json

If you are managing lots of clusters this might be an easier approach.

A: I found the right answer here.
The correct format to run this command on azure is:
databricks clusters create --json '{ "cluster_name": "my-cluster", "spark_version": "4.1.x-scala2.11", "node_type_id": "Standard_DS3_v2", "autoscale" : { "min_workers": 2, "max_workers": 50 } }'

A: databricks clusters create --json "{ "cluster_name": "custpm-cluster", "spark_version": "4.1.x-scala2.09", "node_type_id": "Standard_DS3_v2", "autoscale" : { "min_workers": 2, "max_workers": 50 }}"


text:
Q: Vue js v-for and css nth-child v-for seems to mess up element index. i have the following code:

then in my code:

{{n}}

here child 2 doesn't exists. CSS styles only applied if child 1 is specified.
any help would be appreciated

A: .grid:nth-child(2) means every .grid element that is the second child of its parent. But since your v-for is on the containing div it's actually creating a container around each .grid so there are no .grid elements that are second children.  I think you probably actually want the v-for on the .grid element.

new Vue({
  el: '#app',
  data() {
    return {
      posts: [1,2,3,4,5]
    }
  },
});
.grid:nth-child(2) {
 clear: left;
 background-color: gray;
 border: 1px solid yellow;
 }

{{n}}


text:
Q: Visual Studio Code setting delete empty line How can I delete red box empty line? When scrollbar touch bottom, empty line will appear, I want to delete these empty line.

A: Those are technically not lines (see they don't have line number), but a generated visual space below the last line of your file.
You can turn off this feature by adding the following to your preferences (File > Preferences Settings):
"editor.scrollBeyondLastLine": false,

By doing this, the last line of your file will be at the bottom of the editor pane when you scroll down to the maximum.


text: Q: Does C create a seperate frame in Stack for a function which has an array as an argument How does C represent the function which has an array as an argument in Memory? Does it create a separate frame for it in the stacke? If so, how does it fill in the passed array "by reference"? Can you explain the logic behind this process?


text:
Q: call a controller and method on select change with rails i want to call a AJAX query on select change.
I found this code fragment, but it doesnt work on rails 4, or im doing it wrong
<%= f.select(:resource_id, Resource.all.collect {|resource| [ resource.name, resource.id ] }, :class => "medium", :onchange => remote_function(:url => {:controller => 'controller', :action => 'action'})) %>

and im geting this error
undefined method `remote_function' for #<#<Class:0x007f3daff24a88>:0x007f3d9c670210>

any ideas what im doing wrong ?

A: The remote_function has been deprecated and removed from rails. You need to write some javascript now (very simple though).
Unless you are willing to install prototype-rails gem, which will add this helper back to your rails.

A: This should give you a hint:
<%= f.select(:resource_id, Resource.all.collect {|resource| [ resource.name, resource.id ] }, :class => "medium" %>

#javascript code to make an Ajax call:
$('select#your_model_name_resource_id').on('change', function(event) {
  var selected_resource_id = $(this).val();
  $.ajax('/relative/path/to/your/action', data: { id: selected_resource_id })
})

When a user change the value of the select, it should perform an Ajax request to your server at this location: /relative/path/to/your/action?id=12 (if id selected was twelve)


text:
Q: finding maximum value in python list of tuples I have a list of tuples (list):
('2015-06-19', 3453455, 5, 'Scheduled')
('2015-05-19', 6786788, 6, 'Overdue')
('2015-04-19', 2342344, 2, 'Not Received')
('2015-03-19', 9438549, 0, 'Not Received')
('2015-02-19', 6348759, 7, 'Not Received')

When I run this, I get this:
>>> print(max(list))
('2015-06-19', 3453455, 5, 'Scheduled')

Obviously, max(list) determined the max based on the first value in the list of tuples. I'm just wondering if this is the default behavior of max(list) in regards to a list of tuples; to check only the first item in the tuple?
And, what if I wanted to return the tuple with the maximum based on the second item/column. How would I do that?

A: You can specify which field to use for comparison using lambdas
max(list,key=lambda x:x[1])

or alternatively, using itemgetter
from operator import itemgetter
max(list,key=itemgetter(1))


text:
Q: Getting Milliseconds elapsed between arbitrary date and Epoch time If I write a simple method to return the milliseconds between epoch time and DateTime.UtcNow, I get a proper answer.  However, if I write a method to return the milliseconds between some arbitrary date and epoch time, the last three digits are always zero. 'Some arbitrary date' means that I pass in to the method the output of DateTime.Parse("arbitrary date string").  As near as I can make out, the DateTime object returned by .Parse is not returning all the significant digits.
Test method:
    static void GetMillis()
        {
            DateTime dUtc = DateTime.UtcNow;
            DateTime epoch = new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc);
            double utcmillis = (dUtc - epoch).TotalMilliseconds;
            String timestamp = dUtc.ToString();
            DateTime arbitrary = (DateTime.Parse(timestamp));
            Console.WriteLine("Milliseconds between DateTime.UtcNow {0} \nand epoch time {1} are {2}", dUtc, epoch, utcmillis);
            Console.WriteLine("Milliseconds between arbitrary date {0} \nand epoch time {1} are {2}", arbitrary, epoch, (arbitrary - epoch).TotalMilliseconds);
        }

Output:
C:\src\vs\epochConverter\epochConverter\bin\Debug
{powem} [54] --> .\epochConverter.exe -debug
Milliseconds between DateTime.UtcNow 8/26/2012 11:12:31 PM
and epoch time 1/1/1970 12:00:00 AM are 1346022751385.8
Milliseconds between arbitrary date 8/26/2012 11:12:31 PM
and epoch time 1/1/1970 12:00:00 AM are 1346022751000

I don't know if I'm doing something grotesquely wrong or not understanding the math here. I've researched in MSDN and can't find anything relating to this difference.  I really would like to be able to compute the millis as described -- is it possible?
Thanks.
mp

A: You want to examine the intermediate values of:
String timestamp = dUtc.ToString();

Just what it returns will depend on your local settings, but it'll be something like 8/26/2012 11:12:31, which is only accurate to the nearest second.
Parsing that of course gives a date-time with 0 milliseconds.
It is therefore correct that your milliseconds-since-epoch method has zeros at that point.
If however you did something like:
arbitrary = new DateTime(2012, 8, 26, 11, 12, 31, 123);

You'd get those 123 milliseconds influencing the result. You can also use a ToString and a ParseExact that includes fractions of a second, or a whole slew of other ways of obtaining a DateTime.
In all, your milliseconds-since-epoch worked perfectly, but your way of getting a date to test it was flawed.

A: The default DateTime.ToString() format does not include the milliseconds and this is where the data is being lost; it happens before the Parse. To obtain the milliseconds in the string representation, use a custom format:
DateTime.UtcNow.ToString()
// -> 8/26/2012 11:37:24 PM
DateTime.Parse("8/26/2012 11:37:24 PM").Millisecond
// -> 0

DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK")
// -> 2012-08-26T23:41:17.3085938Z
DateTime.Parse("2012-08-26T23:41:17.3085938Z").Millisecond
// -> 308

See The Round-trip ("O", "o") Format Specifier
 to type less. Or, in this case, consider avoiding the conversion entirely :-)
The math is sound.

A: The math looks reasonable here.  Don't forget there are 1000 milliseconds in a 1 second, so any date computation from an arbitrary time that does not include milliseconds vs an almost identical time that includes milliseconds will have an error of +/- 1000 milliseconds.


text:
Q: How can I print certain rows from a CSV in pandas My problem is that I have a big dataframe with over 40000 Rows and now I want to select the rows from 2013-01-01 00:00:00 until 2013-31-12 00:00:00
print(df.loc[df['localhour'] == '2013-01-01 00:00:00'])

Thats my code now but I can not choose an intervall for printing out ... any ideas ?

A: One way is to set your index as datetime and then use pd.DataFrame.loc with string indexers:
df = pd.DataFrame({'Date': ['2013-01-01', '2014-03-01', '2011-10-01', '2013-05-01'],
                   'Var': [1, 2, 3, 4]})

df['Date'] = pd.to_datetime(df['Date'])

res = df.set_index('Date').loc['2010-01-01':'2013-01-01']

print(res)

            Var
Date
2013-01-01    1
2011-10-01    3

A: Make a datetime object and then apply the condition:
print(df)

date
0   2013-01-01
1   2014-03-01
2   2011-10-01
3   2013-05-01

df['date']=pd.to_datetime(df['date'])
df['date'].loc[(df['date']<='2013-12-31 00:00:00') & (df['date']>='2013-01-01 00:00:00')]

Output:
0   2013-01-01
3   2013-05-01


text:
Q: android layout large image I have a large image myImage.png (its dims are 1536 x 784):

I want this image to be placed at the bottom of my layout scaled uniformly and fitting the width:

Layout is
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/myImage"
        android:adjustViewBounds="true"
        android:layout_alignParentBottom="true"
        android:scaleType="fitCenter" >
    </ImageView>

</RelativeLayout>

I've tried dozens of combinations for layout_width, layout_height, adjustViewBounds and scaleType and nothing helped: it always looks as follows:

Help me please.

A: As someone says, use src instead of background:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/myImage"
        android:adjustViewBounds="true"
        android:layout_alignParentBottom="true"
        android:scaleType="fitCenter" >
    </ImageView>

</RelativeLayout>

A: You are using an ImageView. ImageViews use the src attribute to indicate which image to use and to apply the scaleType to.
background, is, as name suggests, merely a background attribute, made to be displayed on that whole background thing.

A: try this:
<ImageView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/myImage"
    android:adjustViewBounds="true"
    android:layout_alignParentBottom="true"
    android:scaleType="fitcenter" >
</ImageView>


text:
Q: ANSIBLE - How create an array with stdout_lines filter by column Morning,
with ansible i have this stdout_lines :
ok: [localhost] => {
    "msg": [
        "1 peot 11135198 NY",
        "1 LIOS 106075056 berlin",
        "1 EASD 10828842 london",
        "1 APES 20789896 local",
        "1 PZSA 21705924 paris"
    ]
}

I need to get the second and fourth column and store it in an array . but I don't find example with filter on column.
so what is the better solution ? with Ansible ou in Jinja2 ?
thanks for your help.

A:
Q: "I need to get the second and fourth column and store it in an array."

A: It's possible to use regex_replace. For example
    - set_fact:
        myarray: "{{ stdout_lines|
                     map('regex_replace', myregex, myreplace)|
                     list }}"
      vars:
        myregex: '^\s*(.*)\s+(.*)\s+(.*)\s+(.*)\s*$'
        myreplace: '\2 \4'
    - debug:
        var: myarray

give
    "myarray": [
        "peot NY",
        "LIOS berlin",
        "EASD london",
        "APES local",
        "PZSA paris"
    ]

Is this what you're looking for?

A: I try to decline your code , but something escapes me .
for get the 2 first column of find result.stdout_lines :
extract :
-rwxr-xr-x 1 root root 11135198 Sep 25  2018 /root/setup/silinstall/nnstall
-rw-r--r-- 1 root root 106075056 Dec 19 14:33 /usr/lib/locale/locale-archive
-rwxr-xr-x 1 root root 10828842 Jan 27  2015 /usr/lib/libsssymm-dmx.so

if i want only the first and 5th columns , i set the vars like this
  vars:
    myregex: '^\s*(.*)\s+(.*)\s+(.*)\s+(.*)\s+(.*)\s+(.*)\s+(.*)\s+(.*)\s+(.*)\s*$' (number of columns)
    myreplace: '\1 \5'

the result :
    "myarray": [
        "-rwxr-xr-x 1 Sep",
        "-rw-r--r-- 106075056",<-----------why this error ???
        "-rwxr-xr-x 1 Jan",
        "-rwxr-xr-x. 1 Aug",
        "-rwxr-xr-x 1 Sep"
    ]
}

I don't understand why i get the wrong column.


text:
Q: Nginx as apache reverse proxy giving 404's on .htaccess rewrite I'm trying to use Nginx as reverse proxy with Apache to cache static files, etc.
I'm having an issue on a new install, that it's not passing on URIs to Apache.
Basically I have a vBulletin forum, and I'm using vBSEO as the SEO proxy.
The problem is it's generating 404s for every URL, except files that already exist.

A: Could you possibly give us the relevant portion of your nginx configuration? A.t.m. we cannot guess what's wrong (although one might:  using 'localhost' when not in the hosts file, so not resolving to 127.0.0.1, wrong portnumber for apache, forgetting to add a host header, etc.). Normally, It'd be something like:
server {
    listen       80;
    server_name  www.example.com;

    # normally some checking here for static content which exists as file
    # like images, js, etc, with a 'break', with at the end:

    location / {
        proxy_pass         http://127.0.0.1:<portnumber apache is on>/;
        proxy_redirect     off;
        proxy_set_header   Host $host;
    }
}

A: Well I traced it down to the SEO friendly plugin ( vBSEO ). It was producing links with .html extension and it seems nginx had it set for caching. Since those links didn't exist physically, it was producing the 404s.


text:
Q: iOS Development: What's a simple way to calculate the number of seconds that have passed between two events? I need to calculate the number of seconds that have passed between two events on the iPhone.  To do so, I need to store the time that the first event occurred and check it against the time the second event occurred to see if more than 30 seconds has passed.
I'm about to begin trying to accomplish this using the NSDate class, but I was wondering if there's a simpler way to do this without using objects, as I would prefer to store simple, intrinsic values instead of objects.
Thanks for your wisdom!

A: If you really want to avoid storing objects, you can do something like:
double startTime = [[NSDate date] timeIntervalSince1970];

//Run your other code

double endTime = [[NSDate date] timeIntervalSince1970];

if (endTime - startTime > 30) {
  //30 seconds have passed
}

A: have you seen UIEvent's timestamp?
example:
double event1Timestamp, event2Timestamp; ///< ivars in your class?

{ // some function/method body
  event1Timestamp = event1.timestamp;
}

{ // some other function/method body
  /*** later that day ***/
  event2Timestamp = event2.timestamp;
  if (30 <= (event2Timestamp-event1Timestamp)) {
    printf("ok, it's been 30 seconds");
  }
}

where event1 and event2 are naturally the incoming events

A: You can use

[NSDate dateWithTimeIntervalSinceReferenceDate:anotherDate];

or use the initWithTimeIntervalSinceReferenceDate: method


text:
Q: Locality defined in terms of the Lagrangian density I've been reading through Matthew Schwartz's book "Quantum Field Theory and the Standard Model" and in chapter 24 there is a section on locality (section 24.4). In it he defines locality in terms of the Lagrangian stating
" We take locality to mean that the Lagrangian is an integral over a Lagrangian density that is a functional of fields and their derivatives evaluated at the same point."
Which is all well and good, but then he further elaborates to say that
"To be clear, this definition is mathematical, not physical: it is a property of our calculational framework, not of observables."
This part confuses me as I thought that the whole motivation was physical, i.e. that objects at different spacetime points should not be able to directly interact with one another? It makes sense to me that, as the Lagrangian density characterises the dynamics of a physical system at a given spacetime point, and locality demands that the dynamics of the system at that given point should depend only on the state of the system at that point (i.e. the field configuration and how it's changing at that point), then clearly the Lagrangian density should depend on no more than the state of the system at that point, i.e. the field configuration and its rate of change (in spacetime)?! Maybe I'm missing something?

A: For a classical field theory or a classical field and particle theory you want the dynamics of that stationary path. (Or the dynamics of one of the stationary paths.) But you consider all kinds of dynamics, and just reject the ones that don't have a stationary action.
If you know the Euler-Lagrange equations you are aiming for are going to just have/be derivatives at points, it makes sense to start with that, because it makes it easier to get that.
For a quantum field theory, you have to sit back and ask what the observables you are aiming for are. One possibility is that you are computing a scattering matrix. In which case your observables in a sense could be on shell free particle states.
If you want to think about it as a distinction between on shell and off shell interactions that might be what you are aiming for.
Off shell interactions are not what you are looking for as part of your observables. So they are purely about the math you are using to describe relationships between on shell states.
So it might not seem a big deal whether your density is written in terms of derivatives of the field or not. What matters is whether you included all the right on shell states and properly got the relationships between them.
There isn't a location to an on shell state, they are separated more in the sense of being approximately free than in having approximate locations that don't overlap. But the physical distinction and observables is likely the on shell states and their relationships. The mathematics is just how you compute them. So locality could be about how you compute the relationships. And so aiming for local or nonlocal might not be the key compared to having the right on shell states and relationships between them.
I couldn't read page 475 so I could be totally wrong about what the author intended.


text:
Q: Understand squid access.log I would like to understand the access.log of the squid application, the various codes and what they mean for example
TCP-MISS/502
what does it mean and how does it come about?
Is there an appendix for this?

A: The log format is user-definable, but odds are good you're using the default native log format. The Squid cache FAQ describes the native log format in detail, including the result code you're asking about.

A: check out the squid wiki.
TCP_MISS The requested object was not in the cache.


text:
Q: SQL excluding rows using INNER JOINs throws error: expected 'UDFCALLNAME' (Teradata) Join Tables
I have a query where I inner join:

*

*first table (A)

*second table (B)

*third table (C)

Exclude IDs
I would like to exclude rows which meet some conditions of (C) from result joining (A) with (B).
I have the query as below but I am not getting the desired results.
Any help with excluding IDs in (C) from (A x B) would be greatly appreciated. I want to exclude IDs who are on those meds.
Error
I am also getting an error:
expected 'UDFCALLNAME' keyword between ')' and ')'

SQL on Teradata
 select distinct first_visit.pat_id,
            first_visit.PatientMRN,
            first_visit.PatientName,
            cast(contact_date as  date format 'yyyy-mm-dd') as visit_date,
            first_visit.hsp_account_id as hsp_acct
from
(
SELECT  distinct pat.pat_id,
    pat.PAT_MRN_ID as PatientMRN,
    pat.PAT_NAME as PatientName,
    contact_date,
    cast(pat.Birth_Date as  date format 'yyyy-mm-dd') as DOB,
    cast(contact_date as date) - cast( pat.birth_date as date) year (4) AS PatAge,
   enc.enc_type_c,
   dept.specialty,
   dept.department_name,
    specName.NAME,
    prov_name,
    acct.hsp_account_id
FROM  Patient pat
inner JOIN  HSP_ACCOUNT acct on  acct.PAT_ID = pat.PAT_ID
inner JOIN  Pat_enc enc on  enc.PAT_ID = pat.PAT_ID
inner join clarity_ser_dept ser  on ser.prov_id = enc.visit_prov_id
inner join clarity_ser prov on prov.prov_id = ser.prov_id
inner join CLARITY_SER_SPEC spec on enc.visit_prov_id = spec.PROV_ID
inner join ZC_SPECIALTY specName on specName.SPECIALTY_C = spec.SPECIALTY_C and spec.LINE=1 and specName.NAME = 'xxx'
inner join CLARITY_DEP Dept on Dept.DEPARTMENT_ID = enc.DEPARTMENT_ID  and dept.specialty = specname.name
inner join CLARITY_LOC provLoc on provLoc.LOC_ID = Dept.REV_LOC_ID
where patAge > 55
and cast(contact_date as  date format 'mm/dd/yyyy') >= '10/01/2018'
and ACCT_CLASS_HA_C  =  '1207'
and acct.CODING_STATUS_C = 4
and acct.ACCT_BILLSTS_HA_C NOT IN (40, 60, 99)
AND SUBSTR(CAST (acct.HSP_ACCOUNT_ID AS VARCHAR(18)),4,1) IN ('1','3')
and enc_type_c  = '101'
group by 1,2,3,4,5,6,7,8,9,10,11,12
qualify row_number() over (partition by PatientMRN  order by contact_date DESC) =1) first_visit

inner join
(select problem.pat_ID, edg.DX_ID, noted_date
from problem_list problem
inner join clarity_edg edg on problem.DX_ID = edg.DX_ID
--where pat_id = '212000001293964'
and DX_name like any ('%Atrial FLutter%', '%Atrial Fib%')
) DX on DX.pat_id = first_visit.pat_id and DX.noted_date < first_visit.contact_date

/* exclude */
left  join
(select distinct pat_id
from (select pat_id from order_med ordmed
inner join RX_MED_TWO rxmed  on ordmed.medication_id = rxmed.medication_id
inner join ZC_ADMIN_ROUTE  zc on ADMIN_ROUTE_C = zc.med_route_c
where medication_name  like any ( '%Coumadin%',  '%Eliquis%'))) meds
on first_visit.pat_id = meds.pat_id
where meds.pat_id is null;

Thank you!
JH

A: First, there is a bunch of problems with you sample SQL.
Using (Select * from A)Table_A in a FROM clause is unnecessary, as it is the same as A Table_A.  This simplifies your sample to the following:
select distinct Table_ABC.id,
                 Table_ABC.name,
         Table_ABC.Age
 from
(
  A Table_A

  inner join (B Table_B on Table_A.id = Table_B.id) Table_AB

  inner join (C Table_C on Table_C.id <> TableAB.id and (condition)
)Table_ABC

Next, if tables A, B, and C have a field named id, then Table_ABC.id is still going to be ambiguous.  Instead, specify the table you want to use for the id field.
I'd also get rid of the Table_AB and Table_ABC aliases.
I also question the aliases Table_A, Table_B, and Table_C.
Typically one sees aliases to make the table names shorter (when not aliasing to avoid ambiguity) but here you make them longer.
select distinct Table_A.id, Table_A.name, Table_A.Age
from A Table_A
  inner join B Table_B on Table_A.id = Table_B.id
  inner join C Table_C on Table_C.id <> Table_A.id and (condition)

Now, finally, to exclude when the join matches on C, do an outer join and use a where clause for the NULL values created by the outer join.
select distinct Table_A.id, Table_A.name, Table_A.Age
from A Table_A
  inner join B Table_B on Table_A.id = Table_B.id
  left outer join C Table_C on Table_C.id = Table_A.id and (condition)
where Table_C.id is NULL


text:
Q: How to split a large mp3 into the different tracks (also in mp3)
Possible Duplicate:
How can I split a mp3 file?

I've got this huge mp3 file of the recording of a concert and I want to split each music into it's track so that when I burn into a cd audio it can have each track with a different song. What's the best apps for doing this?

A: Take a look at this: How can I split a mp3 file? May be helpful for your case.
This will work on both wav, ogg, mp3 and other formats.
Good luck!


text:
Q: post request not working, claims body data is not present when it is I am trying to update my table with a new row in prisma and i cant seem to find what the problem is.
my post looks like this:

app.post(`/content`, async (req, res) => {
  const result = await prisma.content.create({
    data: {
      title: req.body.title,
      content: req.body.content,
    },
  })
  res.json(result)
})

My model looks like this:

model content {
  id        Int      @id @default(autoincrement())
  title String
  content String
}

I call my post like this:

createContent() {
  let identifier = this.content.length + 1
  let newContent = { data: { id: identifier, title: 'Sample tekst', content: "Sample tekst" } }
  this.addContent(newContent.data)

  fetch('http://localhost:3000/api/content', {
    method: 'post',
    body: JSON.stringify(newContent)
  })

  .catch(error => {
    console.error('Error:', error)
  })
}

I tried adding id: req.body.id to the data object in my post but it didnt make a difference.
Also tried removing id from the newContent object, still same error.
The error i get is:

ERROR                                                                                20:44:23
Invalid `prisma.content.create()` invocation:

{
  data: {
    id: undefined,
+   title: String,
+   content: String
  }
}

Argument title for data.title is missing.
Argument content for data.content is missing.

Note: Lines with + are required

A: I've fixed the problem. There's 2 ways of fixing this.
Solution 1:
Add headers.

fetch('http://localhost:3000/api/content', {
  method: 'post',
  body: JSON.stringify(newContent),
  headers: { 'Content-type': 'application/json; charset=UTF-8' }
})

Solution 2:
Install axios with npm i axios,like a real man then import it and make your post as following:

axios.post('http://localhost:3000/api/products', newProduct)
  .then((response) => {
  console.log(response)
})
  .catch((error) => {
  console.log(error);
})


text:
Q: database is catching wrong result from javascript can anyone help me please? So I'm making a web app where a user can crack the vault code by clicking the numbers from 1-40. They are only allowed to click 6 sets of numbers for example "6", "20", "1", "40", "27", "15". So I have a data variable "guess" in my database with int(12) as the var numbers in this JS below. The problem is whenever I try "40", "39", "38", "37", "36", "35". The database will catch "2147483647" and I'm getting confused why, there must be something wrong in what I'm doing. I'm not really professional with JS and I'm just following some guides. This was working when I had the 0-9 numbers in the vault and int(6) in the data var "guess" inside the database. Please help, thank you!
var numbers     = document.querySelectorAll('.number');
var screenSpans = document.querySelectorAll('#screen span');
var clear       = document.getElementById('clear');
var enter       = document.getElementById('enter');
var errorModal  = document.getElementById('digitAmountAlert');
var currEmail   = document.getElementById('currEmail').innerHTML.replace(/\s/g, '');
var lastModal   = document.getElementById('lastModal');
var main        = document.getElementById('main');
var guess       = '';
var reset;

clear.addEventListener('click', function(){
reset = 0;
for (var i = screenSpans.length - 1; i >= 0; i--) {
    if (screenSpans[i].innerHTML != '' && reset == 0){
        screenSpans[i].innerHTML = '';
        reset = 1;
    }
};
});

enter.addEventListener('click', function(){
reset = 0;
for (var i = 0; i < screenSpans.length; i++) {

    // Catch if they have not entered enough digits
    if (screenSpans[i].innerHTML == ''){
        errorModal.className = 'modal';
        setTimeout(function(){
            errorModal.className = 'modal hide';
        }, 4000);

    } else {
        guess = guess+screenSpans[i].innerHTML;
        if (guess.length == 12){
            $.ajax({
                  url: "submit.php",
                  method: "POST",
                  data: { guess: guess, email: currEmail }
            });

            lastModal.className = 'modal';
            main.className = 'hide';
        }
    }
};
guess = '';
});

for (var i = numbers.length - 1; i >= 0; i--) {
numbers[i].addEventListener('click', function(){
    reset = 0;
    nextSpan(this.innerHTML);
});
};

function nextSpan (currNumber){
for (var i = 0; i < screenSpans.length; i++) {
    if (screenSpans[i].innerHTML == '' && reset == 0){
        screenSpans[i].innerHTML = currNumber;
        reset = 1;
    }
};
}

/*
|---------------------------------------------------
| FORM SUBMIT CHECK
|---------------------------------------------------
*/

var submitButton = document.getElementById('startButton');
var form = document.getElementById('form');
var goAhead = true;

submitButton.addEventListener('click', function(){
var i, j, q = [];
for (var i = 0; i < form.elements.length; i++) {
    if (form.elements[i].nodeName == "INPUT"){
        q.push(form.elements[i].name + "=" +     encodeURIComponent(form.elements[i].value));
        var inputValue = encodeURIComponent(form.elements[i].value)
        if ((inputValue == '' || inputValue == null) && (form.elements[i].name != 'online')){
            // NOT COMPLETE
            goAhead = false;
            console.log(form.elements[i].name)
        }
    }
}

if (goAhead){
    // SUBMIT
    document.getElementById('form').submit();
} else {
    this.innerHTML = "Please fill out all the fields & try again";
    setTimeout(function(){
        submitButton.innerHTML = "Let's Play!";
    }, 7000);
    goAhead = true;
}
});


text:
Q: Setting ArcGIS Server 10.2 Data Store Folder as Local vs. Network (UNC) path Is there any difference?
How setting ArcGIS Server Data Store Folder as local vs. network path will affect the publishing process?
I saw warnings in ArcMap 10.1  when I Analyze the MXD before I publish, complaining that network path is used. (Assuming this might slow down the REST service if network access to MXD data is slow)
Example:
My file server has designated shared folder for ArcGIS data called "GisDataStore". It is mapped as local drive on my ArcGIS server, so I can access it both ways:
\MyFileServer\GisDataStore  and  Z:\GisDataStore
I wonder which I should use to Register the "GisDataStore" folder as ArcGIS 10.2 Server datastore.

Here's the warning I am getting:
SEVERITY    STATUS  CODE    DESCRIPTION
Medium      Unresolved  10027   Layer's data source is referenced via a UNC path

A: Always go with the UNC path (\\server\folder) when creating a data store for ArcGIS Server. This is both cleaner (since you can see the machine name in the path directly) and safer (if there will be a problem with disk mapping, you can have troubles accessing the path).
From Esri Help:

When you use UNC paths to reference your data, all GIS server machines
  will look to the correct machine for the data. If you store your GIS
  resources in shared directories, remember that all data source paths
  within the resource must also use UNC paths or relative paths. For
  example, if your map document contains layers from three feature
  classes, the paths to those feature classes must be UNC or relative
  paths.

A good help page on paths: Paths explained: Absolute, relative, UNC, and URL
You are getting this warning in ArcMap because when using UNC paths network file access is typically slower than direct disk access on your local computer. This can of course negatively affect the map drawing performance since it is as a rule would take longer time to get data over the network comparing to accessing the dataset locally.
Since storing the data on a local disk in your case is not an option, you can ignore this warning or even right-click it and mark as exception to avoid getting it again.

A: It all depends on your geodatabase.
If your gdb is read only, and you dont expect it to get updated often, use local fixed path (i.e. c:\gisdata). Make sure you copy your geodatabase on all GIS servers in your server site at the same exact path. This will save you network latency and can get you good performance through data locaility.
If your gdb is frequently updated, it is in-feasible to duplicate it on multiple GIS servers. Here when UNC shared folder comes in handy. You can use geodatabase replication to update this geodatabase to the shared directory(i.e. \hostname\gisdata). Bear in mind that UNC will slow things down for sure.
One last thing. When using UNC, avoid placing your geodatabase on one of the GIS servers. The reason is if that particular server failed you will lose access to your data even though you might have other gis servers up and running. I suggest using a NAS RAID setup to store your geodatabase. Or better of an enterprise geodatabase.
I have written a humble book about ArcGIS for Server Administration, that include good tips. Chapter 1 and 2 discusses the best practices of using UNC path vs physical paths.


text:
Q: Opening a new window using AJAX Want to open a new windows 640px width and 400px height with the url http://www.google.com when you choose an item in a drop down list without pressing any other button.
I want to get it implemented using the AJAX(XMLHttpRequest)


text:
Q: Expectation of a log random variable I have an equation that requires taking the natural log of a random variable. When trying to figure out how to evaluate the expression, I came across this paper:
Y. W. Teh, D. Newman and M. Welling (2006), A Collapsed Variational Bayesian Inference Algorithm for Latent Dirichlet Allocation, NIPS 2006, 1353–1360.
They use a second order Taylor expansion around $_0=\mathbb{E}[x]$ to approximate $\mathbb{E}[\log(x)]$ to obtain
$$\mathbb{E}[\log(x)]\approx\log(\mathbb{E}[x])−\frac{\mathbb{V}[x]}{2\mathbb{E}[x]^2}$$
I can't seem to derive that equation and was wondering if someone might be able to help show that it is true? Also, does that result hold if instead we wanted to evaluate $\mathbb{E}[\log(-x)]$ where $x\in(-\infty,0)$?

A: A second order Taylor expansion around $\mathbb{E}(x)$ gives
$$log(x)\approx log(\mathbb{E}(x))+\frac{1}{\mathbb{E}(x)}\times(x-\mathbb{E}(x))-\frac{1}{2}\frac{1}{\mathbb{E}(x)^2}(x-\mathbb{E}(x))^2$$
Take expectations
$$\mathbb{E}(log(x))\approx  \mathbb{E}(log(\mathbb{E}(x)))+\frac{1}{\mathbb{E}(x)}\times(\mathbb{E}(x)-\mathbb{E}(x))-\frac{1}{2}\frac{\mathbb{V}ar(x)}{\mathbb{E}(x)^2}$$
because the 2nd term vanishes and the expectation of a constant is the constant:
$$\mathbb{E}(log(x))\approx  log(\mathbb{E}(x))-\frac{1}{2}\frac{\mathbb{V}ar(x)}{\mathbb{E}(x)^2}$$


text:
Q: What FrontierNav locations cannot be reached on foot? Some FrontierNav locations seem to only be available by a Skell with flight capabilities. What locations are these?
It would be helpful if they were relative to ones that can be reached since I don't believe you can get the ID of the location without actually getting there first.

A: Primordia

*

*The northwest-most one requires a skell to get to it.

*The one just northwest of NLA requires a flying skell also.

Noctilum

*

*All of the Divine Roost ones (the two in the very top left) require a flying skell.

Oblivia

*

*The one in the hole (it's the one that everyone tries to jump to when they first get a skell) doesn't need a flying skell but it helps immensely.

*There is a flying island in the northeast area of Oblivia (it's just south-east of the most north-east one) that you need a flying skell to get to.

Sylvalum
I actually think you can get all of these on foot.
Cauldros
The island in the bottom-middle-left of cauldros seems to require a flying skell to get to it.

A: The most north-western one in Primordia can actually be reached via flightless skell. You just need some creative climbing. Too bad you need mechanical level 5 to plant.


text:
Q: 401 unauthorized due to directory protection on magento 2 project Is there a way to pass basic authorization and bearer authorization in postman for accessing Magento 2 rest api's. I have defined the directory protection using .htaccess and .htpassword.
For getting a token I can pass basic auth to get a token. But to use that token in other rest calls I need to pass the token using bearer in Authorization
When I submit a call it says 401 unauthorized. It is due to the directory protection credentials when the are not supplied. I need to know either we could bypass or is there a way we could both pass basic and bearer authorization for testing in postman or something to do in .htaccess file.
In short directory protection is for Magento 2 store and I need this, but for api's is there any solution to handle this?

A: In short, I don't think there's a way to pass both Auth headers and have it work. What you can do is add the following line to your apache2 config:
Require expr %{REQUEST_URI} =~ m#^/index.php/rest/.*#

Or, in context:
    <Directory /path/to/directory/>
        AuthType Basic
        AuthName "Password Required"
        AuthUserFile "/etc/apache2/.htpasswd"
        AllowOverride all
        Require valid-user
        Require expr %{REQUEST_URI} =~ m#^/index.php/rest/.*#
   </Directory>

This will allow you to access the REST API without having to provide Basic Auth while preserving Basic authentication for the rest of the site.


text:
Q: Change part of string into * Let's say I have an IBAN: NL20INGB0001234567
How can I change all digits except the last 4 into *:
Input: NL20INGB0001234567
Output: NL20INGB******4567

all digits but NL*20*

A: Using regex:
>>> import re
>>> strs = 'NL20INGB0001234567'
>>> re.sub(r'(\d+)(?=\d{4}$)', lambda m:'*'*len(m.group(1)), strs)
'NL20INGB******4567'

A: Simplest?
import re
s='NL20INGB0001234567'
re.sub(r'\d+(\d{4})$',r'****\1',s)

Result:
'NL20INGB****4567'

A: tmp = ''
iban = 'NL20INGB0001234567'
for i in iban[4:-4]:
     if i.isdigit():
             tmp += '*'
     else:
             tmp += i

iban = iban[:4] + tmp + iban[-4:]

A: >>> iban = "NL20INGB0001234567"
>>> iban[:4] + ''.join(i if i.isalpha() else "*" for i in iban[4:-4]) + iban[-4:]
'NL20INGB******4567'

A: s = "IBAN: NL20INGB0001234567"

s = [ele for ele in s.split(':')[-1] if ele.strip()]

mask = [1 for ele in range(len(s) - 10)] + [0] * 6 + [1] * 4

print ''.join(["*" if mask[i] == 0 else ele for i, ele in enumerate(s)])

Output:
NL20INGB******4567

A: Based on the way you worded the question, I'm assuming you want to format an IBAN string from
##################

to
########******####

Based on this, a simple solution is to write this function:
def ConverterFunction(IBAN):
    return IBAN[:8]+"******"+IBAN[14:]

and call it with this line:
ConverterFunction(<your IBAN here>)

Of course, attaching assignments or prints where necessary.
EDIT: A bit of an explanation might be necessary, too.
Whatever you are using as IBAN is a string, and strings can be sliced. By slicing, a person can pick up parts of a string and leave others behind. It uses the index of each letter's position, like so:
This is OK
0123456789

Note, the index always starts at 0, not 1.
Example of taking string slices:
examplestring = "EXAMPLE!"
print examplestring[:3] # "[:3]" means "from beginning to position 3"
print examplestring[5:] # "[5:]" means "from position 5 to end of string"
print examplestring[3:5] # "[3:5]" means "from position 3 to position 5"

Output:
>> EXAM
>> LE!
>> MPL

So in my solution, what the function ConverterFunction(IBAN) does is:
#Takes string "IBAN"
#Chops off the beginning and end parts you want to save
#Puts them back together with "******" in the middle

Understand?
Happy coding!


text:
Q: Is it possible to load an SSL-encrypted website with a self-signed security certificate in an iPhone application? This is a question that seems to be floating around all over the place, but so far I haven't been able to find a definite answer.
I'm tasked with writing an iPhone application for my company. My company has an SSL-encrypted website with a self-signed certificate. This website is used very frequently, and my employer would like for the site to be easily accessible on an iPhone. My app's function is to provide a method of storing the credentials used to access the site, and when the user opens the app, it automatically sends the stored credentials to the site and skips the login dialog to go straight into the site.
I've set up my app to use a UIWebView and load a request for the site. I've set up the usual authentication methods, such as:
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {...}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {...}

When my app reaches the part of the code where I tell the UIWebView to load the NSURLRequest, it doesn't encounter any of my authentication methods. It jumps straight to didFailLoadWithError and the error tells me that I'm connecting to a site that may only be pretending to be my site because it has a self-signed certificate.
How do I get around this? I've found a few answers involving the NSURLConnection methods, but those methods don't appear to be called before I reach the error and am forced to stop loading the page. I've also found some answers involving overriding "undocumented" methods, but when I try implementing that solution my web view never reaches either "didFailLoadWithError" or "didFinishLoad" and never displays any content.

A: The UIWebKit delegate doesn't forward through any of the NSURLConnection delegate methods to your app. One way to get around this would be to load the page using NSURLConnection and then push it into the UIWebView using -loadData:MIMEType:textEncodingName:baseURL:. Once you've done that you've verified the first page, which (as long as your site doesn't have links off of it), should stay safe.  So, how do we verify a self-signed certificate?
I had to solve this with an OSX App a little earlier this year and, once I figured out what I was doing, it was pretty straightforward, assuming you have a similar setup.   The solution I propose here actually verifies the server certificate (although in my case I was using a private CA, so I added the CA certificate to the trust root, instead of the server certificate, it should work just as well with that).
You'll need to add tests for NSURLAuthenticationMethodServerTrust to both the -connection:canAuthenticateAgainstProtectionSpace: and -connection:didReceiveAuthenticationChallenge: methods so that you can both request interest in and process the Security challenge.
Hope this helps.
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
    // ... implement any other authentication here, such as your client side certificates or user name/password

    if ([[protectionSpace authenticationMethod] isEqualToString: NSURLAuthenticationMethodServerTrust])
        return YES;
    return NO;
}

-(void)connection:(NSURLConnection *)aConnection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    NSURLProtectionSpace *protectionSpace = challenge.protectionSpace;

            // implement your client side auth here for NSURLAuthenticationMethodHTTPDigest or basic or your client-side cert

    if ([[protectionSpace authenticationMethod] isEqualToString: NSURLAuthenticationMethodServerTrust]) {
        // install our private certificates or CAs
        NSString *myCAString = @"<string containing your CA cert>";

        SecCertificateRef certRef = SecCertificateCreateWithData ( NULL, (CFDataRef)[NSData dataFromBase64String: myCAString]);
        NSArray *anchorArray = [NSArray arrayWithObject: (NSObject*)certRef];
        SecTrustSetAnchorCertificates( challenge.protectionSpace.serverTrust, (CFArrayRef) anchorArray);

        SecTrustResultType trustResultType;
        OSStatus err=SecTrustEvaluate(challenge.protectionSpace.serverTrust, &trustResultType);

        if ((!err) && (trustResultType == kSecTrustResultProceed || trustResultType == kSecTrustResultConfirm || trustResultType == kSecTrustResultUnspecified)) {
            [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
        } else {
            CFArrayRef certChain=NULL;
            CSSM_TP_APPLE_EVIDENCE_INFO *statusChain;
            SecTrustGetResult( challenge.protectionSpace.serverTrust, &trustResultType, &certChain, &statusChain);
            [challenge.sender cancelAuthenticationChallenge:challenge];
        }

    } else {
        // Cancel if we don't know what it is about... this is supposed to be secure
        [challenge.sender cancelAuthenticationChallenge:challenge];
    }
}

A: I have managed to do what you desire by using RestKit framework, so yes, I can confirm it can be done. Go see in the RestKit sources how they do it, or just use RestKit. This says how to use SSL with RestKit. In my case, there was one catch - the self signed certificate had to contain the certain extensions, otherwise I always got the kSecTrustResultRecoverableTrustFailure. Go see here, the answer is voted -1 but it actually fixed the problem for me.


text:
Q: How to log into the database under the user? I install postres9 on linux mint 18. I login under default postres user. I try create new user and login under this user.
kalinin@lenovo ~ $ sudo -i -u postgres
postgres@lenovo ~ $ psql
psql (9.5.16)
Type "help" for help.

postgres=# CREATE DATABASE db_test;
CREATE DATABASE
postgres=# CREATE USER user_test WITH PASSWORD 'qwerty';
CREATE ROLE
postgres=#
postgres=#
postgres=# GRANT ALL PRIVILEGES ON DATABASE "db_test" to user_test;
GRANT
postgres=# \du
                                   List of roles
 Role name |                         Attributes                         | Member of
-----------+------------------------------------------------------------+-----------
 postgres  | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
 user_test |                                                            | {}

postgres=# \l
                                   List of databases
    Name     |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges
-------------+----------+----------+-------------+-------------+------------------------
 db_test     | postgres | UTF8     | ru_RU.UTF-8 | ru_RU.UTF-8 | =Tc/postgres          +
             |          |          |             |             | postgres=CTc/postgres +
             |          |          |             |             | user_test=CTc/postgres
 postgres    | postgres | UTF8     | ru_RU.UTF-8 | ru_RU.UTF-8 |

postgres=# \q
postgres@lenovo ~ $ exit
logout
kalinin@lenovo ~ $ sudo -i -u user_test
sudo: unknown user: user_test
sudo: unable to initialize policy plugin

you see what i am creating new user with password and new database. after that i exit from postgres and try login again. But login failed. Please help fix it.


text:
Q: Shared.CellItem' does not implement interface member 'System.IDisposable.Dispose() I am new to c# and am trying to dispose of objects taking up large amounts of memory as I've run memory profiling and need to dispose of some resources and call the finalize method for GC. However IDisposable cant implement my class why is this? and how should I implement IDispose to my class?
 public class CellItem: IDisposable
        {
            public int MedicationDispenseId { get; set; }
            public Enumerations.Timeslot Timeslot { get; set; }
            public DateTime DateAdministered { get; set; }

            public void dispose() {

                if (this.MedicationDispenseId != null ) {
                    this.dispose();

                }
                if (this.Timeslot != null)
                {
                    this.dispose();

                }
                if (this.DateAdministered != null)
                {
                    this.dispose();

                }
            }

        }

A: C# is case-sensitive, you want to name your methods starting with capital letter, i.e.
dispose => Dispose
Also have a look at Implement IDisposable correctly and yet another good answer from John Skeet.


text:
Q: how to store object state before and after setting attribute values i have a class Demo i want to save object value before setting attribute value here is my code
case class Demo (var abc:String)

      val d =Demo("bob")
      var oldDemo=d
      d.abc="joe"

      println("old name is "+oldDemo.abc +" the new name is "+d.abc)

the output printed on the console is
old name is joe the new name is joe

i want to store object value before setting d.abc="joe" so that i can get bob when i do oldDemo.abc
please guide me where i am going wrong and what is the right way to achieve my goal .and i apologize if i am doing something stupid

A: You can use copy() on a case class.
val d1 = Demo("abc")
val d2 = d1.copy()
d1.abc = "def"

// d2 : Demo = Demo(abc)
// d1 : Demo = Demo(def)

A more Scala idiomatic way would be to use immutable case classes:
case class Person(name: String, age: Int)
val bob = Person("Bob", 30)
val joe = bob.copy(name="Joe")

// bob : Person = Person(Bob,30)
// joe : Person = Person(Joe,30)

A: *

*afaik, case classes are meant to be immutable.

*case classes are cheap, so an immutable case class might meet your requirements.

*If you change a mutable object, a reference to that object will not help you to store a previous state. For that you would need a copy of that object.

So, depending on your requirements, I'd do either copy the original object changing select attributes to qasi mutate it
case class Demo(abc: String)

val demo = Demo("foo")
val quasiMutatedDemo = demo.copy(abc = "bar")

or I would have to implement a copy in my mutable class (just because I just could never bring myself to create a mutable case class).
class Demo(var abc: String) {
  def copy: Demo = new Demo(this.abc)
}

val demo = new Demo("foo")
val odlDemo = demo.copy
val mutatedDemo = demo.abc = "bar"

A: The best way to achieve this is to not use mutable variables. Like
case class Demo(abc: String)

val d = Demo("bob")
val newDemo = d.copy(abc = "joe")

println("old name is " + d.abc + " the new name is " + newDemo.abc)


text:
Q: Websocket client in Java - NoClassDefFoundError I have Android project on Eclipse.The main idea is created java websocket client. Client must send message to the server and get some message back. But when I run the app on the emulator, it crashes. In the Log, there is a NoClassDefFoundError. Where is mistake?
My main.xml is very simple :
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
       android:id="@+id/messages"
        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    </LinearLayout>

This MainActivity.java :
package com.ab.mywebsocketclient;

import java.net.URI;
import java.net.URISyntaxException;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends Activity {
private WebSocketClient mWebSocketClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    connectWebSocket();
}

private void connectWebSocket() {
    URI uri;
    try {
      uri = new URI("ws://127.0.0.1:80");
    }
    catch (URISyntaxException e) {
        e.printStackTrace();
        return;
      }
    mWebSocketClient = new WebSocketClient(uri) {
        @Override
        public void onOpen(ServerHandshake serverHandshake) {
            Log.i("Websocket", "Opened");
            mWebSocketClient.send("123");
            }
        @Override
        public void onMessage(String s) {
            final String message = s;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                      TextView msg = (TextView)findViewById(R.id.messages);
                    msg.setText(msg.getText() + "\n" + message);
                }
            });
        }
        @Override
        public void onClose(int i, String s, boolean b) {
            Log.i("Websocket", "Closed " + s);
        }
        @Override
        public void onError(Exception e) {
            Log.i("Websocket", "Error " + e.getMessage());
        }
    };
    mWebSocketClient.connect();
}
}

In to the Manifest.xml I add
uses-permission android:name="android.permission.INTERNET"
And here is the Log:
08-22 10:53:10.974: D/AndroidRuntime(1251): Shutting down VM
08-22 10:53:10.974: D/AndroidRuntime(1251): --------- beginning of crash
08-22 10:53:10.991: E/AndroidRuntime(1251): FATAL EXCEPTION: main
08-22 10:53:10.991: E/AndroidRuntime(1251): Process: com.ab.mywebsocketclient, PID: 1251
08-22 10:53:10.991: E/AndroidRuntime(1251): Process: com.ab.mywebsocketclient, PID: 1251
08-22 10:53:10.991: E/AndroidRuntime(1251): java.lang.NoClassDefFoundError: Failed resolution of: Lorg/java_websocket/client/WebSocketClient;
08-22 10:53:10.991: E/AndroidRuntime(1251):     at com.ab.mywebsocketclient.MainActivity.connectWebSocket(MainActivity.java:27)
08-22 10:53:10.991: E/AndroidRuntime(1251):     at com.ab.mywebsocketclient.MainActivity.onCreate(MainActivity.java:22)
08-22 10:53:10.991: E/AndroidRuntime(1251):     at android.app.Activity.performCreate(Activity.java:5937)
08-22 10:53:10.991: E/AndroidRuntime(1251):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
08-22 10:53:10.991: E/AndroidRuntime(1251):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
08-22 10:53:10.991: E/AndroidRuntime(1251):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
08-22 10:53:10.991: E/AndroidRuntime(1251):     at android.app.ActivityThread.access$800(ActivityThread.java:144)
08-22 10:53:10.991: E/AndroidRuntime(1251):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
08-22 10:53:10.991: E/AndroidRuntime(1251):     at android.os.Handler.dispatchMessage(Handler.java:102)
08-22 10:53:10.991: E/AndroidRuntime(1251):     at android.os.Looper.loop(Looper.java:135)
08-22 10:53:10.991: E/AndroidRuntime(1251):     at android.app.ActivityThread.main(ActivityThread.java:5221)
08-22 10:53:10.991: E/AndroidRuntime(1251):     at java.lang.reflect.Method.invoke(Native Method)
08-22 10:53:10.991: E/AndroidRuntime(1251):     at java.lang.reflect.Method.invoke(Method.java:372)
08-22 10:53:10.991: E/AndroidRuntime(1251):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
08-22 10:53:10.991: E/AndroidRuntime(1251):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
08-22 10:53:10.991: E/AndroidRuntime(1251): Caused by: java.lang.ClassNotFoundException: Didn't find class "org.java_websocket.client.WebSocketClient" on path: DexPathList[[zip file "/data/app/com.ab.mywebsocketclient-2/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
08-22 10:53:10.991: E/AndroidRuntime(1251):     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
08-22 10:53:10.991: E/AndroidRuntime(1251):     at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
08-22 10:53:10.991: E/AndroidRuntime(1251):     at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
08-22 10:53:10.991: E/AndroidRuntime(1251):     ... 15 more
08-22 10:53:10.991: E/AndroidRuntime(1251):     Suppressed: java.lang.ClassNotFoundException: org.java_websocket.client.WebSocketClient
08-22 10:53:10.991: E/AndroidRuntime(1251):         at java.lang.Class.classForName(Native Method)
08-22 10:53:10.991: E/AndroidRuntime(1251):         at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
08-22 10:53:10.991: E/AndroidRuntime(1251):         at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
08-22 10:53:10.991: E/AndroidRuntime(1251):         at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
08-22 10:53:10.991: E/AndroidRuntime(1251):         ... 16 more
08-22 10:53:10.991: E/AndroidRuntime(1251):     Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
08-22 10:53:16.681: I/Process(1251): Sending signal. PID: 1251 SIG: 9

A: In Android Studio you could try adding a compile line to your build.gradle:
compile 'org.java-websocket:Java-WebSocket:1.3.0'

found from http://mvnrepository.com/artifact/org.java-websocket/Java-WebSocket/1.3.0

A: In your app level build.gradle file add these lines
 repositories {
mavenCentral()
 }

in dependencies{} add this implementation
 implementation "org.java-websocket:Java-WebSocket:1.3.0"


text:
Q: How to quarantine a specific subversion revision? I have a revision that has been committed to SVN trunk which I would like to roll back.  However, I would like to retain the changes in some fashion such as a branch or even a patch file.  Any suggestions?

A: Reverse-merge (I think that was the term), commit and that's all.
For the "reverse-merge" part - TSVN has this cool feature called "Revert to this revision" (and "Revert changes from this revision"), accessible through the Log dialogue.
The main purpose of a VCS is to keep history of your changes. You could always go back to this particular revision by using "Update to revision..." or by using the aforementioned "shortcuts".

A: You can specify a particular revision when you do a copy (ie. branch).
Something like:

svn copy -rsome_revision trunk branches/interesting_branch

So roll back your changes in your trunk and then do your branch, specifying the revision before you commited your rollback (merge).
You can also capture the differences as a patch file, if that's what you really want to do, by redirecting the output of an svn diff to a text file.
But that's usually not necessary, as the subversion merge commands give you this flexibility already.


text:
Q: Algorithm of a complement graph using adjacency matrix How to implement a complement graph which is given with adjacency matrix (literally any graph)?
I am wondering how to make a code of that graph, but I am not sure how to complete it.
I usually use pseudocode for these "early" implementations. This is what I have come up so far,
it is just the beginning of the code. I know how to draw the complement graph, I know it's definitions, but I struggle with finishing it with the code.

Complement (G,s)
int Arr[1...size(V)]
queue Q
  for i=1 to size(V)
    Arr[i]=0

A: Your question is to find the complement of a graph. Its solution depends on the representation of graph used. In the question you have mentioned that adjacency matrix will be used to represent the graph.
Pseudocode

Here is a function which takes a graph as input and outputs the complement graph. Both the graph are represented using adjacency matrix.
G = Graph
G.V = graph vertices
CG = complement graph

Complement(G)

1: for i = 0 to G.V
2:     for j = 0 to G.V
3:         if i == j: continue
4:         if G[i][j] = 0: CG[i][j] = 1
5:         else CG[i][j] = 0
6:
7: return CG


text:
Q: stretching one item in listview I have a listview with a variable number of items. When there is to few items to fill the entire screen, then i want background inside the footer to stretch all the way to the imageview in the bottom of screen. How can i achieve that?
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/savings_details_activity_layout"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

  <ListView
    android:id="@+id/default_list_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fadeScrollbars="true"
    android:footerDividersEnabled="false"
    android:headerDividersEnabled="false"
    android:smoothScrollbar="true"
    android:listSelector="@color/transparent" />

  <ImageView
    android:id="@+id/bottom_bar"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:src="@drawable/action_bar_background"
    android:layout_alignParentBottom="true" />
</RelativeLayout>

List items
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:paddingLeft="@dimen/margin_10dp"
android:paddingRight="@dimen/margin_10dp" >

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_marginLeft="@dimen/margin_10dp"
    android:layout_marginRight="@dimen/margin_10dp"
    android:layout_toLeftOf="@+id/list_item_value"
    android:layout_toRightOf="@+id/header_image"
    android:orientation="vertical">

    <TextView
        android:id="@+id/list_item_header"
        style="@style/LargeTextWhiteWithShadow"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:singleLine="true"
        android:text="header" />

    <TextView
        android:id="@+id/list_item_sub_header"
        style="@style/SmallTextLightBlueWithShadow"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:singleLine="true"
        android:text="sub header" />
</LinearLayout>

<TextView
    android:id="@+id/list_item_value"
    style="@style/LargeTextWhiteWithShadow"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_marginRight="@dimen/margin_5dp"
    android:layout_alignParentRight="true"
    android:ellipsize="end"
    android:singleLine="true"
    android:text="value"/>
</RelativeLayout>

I have a listview footer which is just an image. I do not care if i stretch the listview footer or the last item in the list.

A: Consider using layout:weight. You should definetely be able to achieve using weights.
More information http://developer.android.com/guide/topics/ui/layout-objects.html#linearlayout


text:
Q: how to use Amazon SWF internal? I would like to try Amazon SWF development on my pc. But, It seems to me that I must register to Amazon AWS cloud in order to use Amazon Simple Workflow. What I need is to run all Amazon stuff in a single machine without the need of Amazon hosted services (or authentication).
The documentation for Amazon Simple Workflow Service is here.
Can you please help?

A: You could run the workflow locally using the aws test framework. In this case everything (activites and decision workers) will run locally on the instance that you will be running the test framework, only that no swf api will be invoked. So you can test the orchestration logic of the decision worker without needing a aws account.

A: Using cloud services offline doesn't make much sense. You will definitely need to sign up for an AWS account to be able to play with SWF. There is a free tier which should be sufficient for your development.