text:
Q: SAS : how to test if a variable is numeric I'm searching for a simple function to tell me if a given variable of a given dataset is numeric or not.
I would like to use it like this in an if statement in macro language:
%if isNumeric(ds,var) %then %do ...

But I can't find any way to achieve this simply. Do you have any idea if this is feasible?
I know it's probably trivial, but any help would be appreciated!
Thanks!

A: Assuming you want to know the actual type, and not the contents of a variable, there is a vartype(dsid,var-num) function which has the exact specifications you need, excepting it takes var-num not var-name.  This example from the documentation should get you started; you can adapt this to use it to figure out a specific variable.
%let dsid=%sysfunc(open(mydata,i));
%let varlist=;
%do i=1 %to %sysfunc(attrn(&dsid,nvars));
  %if (%sysfunc(vartype(&dsid,&i)) = N) %then
     %let varlist=&varlist %sysfunc(varname
                                 (&dsid,&i));
%end;
%let rc=%sysfunc(close(&dsid));

A: In Data Step using vtype function, we can also determine the type of a give variable from a dataset.
data _NULL_;
  set  sashelp.class (obs=1);
  call symput('numvar',ifc(vtype(sex)='N','YES','NO' ));
run;
%put |&numvar|;

or, instead of call symput, we may use the following statement for elsewhere purposes.
if ifc(vtype(sex)='N','YES','NO' )='YES';

A: You recently edited your question so I thought I'd contribute with the following "simple function":
%if %mf_getvartype(sashelp.class,age)=N %then %put This var is numeric;
%if %mf_getvartype(sashelp.class,name)=C %then %put This var is character;

The mf_getvartype macro function is available in the SASjs core library here, and reproduced below:
/**
  @file
  @brief Returns variable type - Character (C) or Numeric (N)
  @details
Usage:
      data test;
         length str $1.  num 8.;
         stop;
      run;
      %put %mf_getvartype(test,str);
      %put %mf_getvartype(work.test,num);
  @param libds Two part dataset (or view) reference.
  @param var the variable name to be checked
  @return output returns C or N depending on variable type.  If variable
    does not exist then a blank is returned and a note is written to the log.
  @version 9.2
  @author Allan Bowe
  @copyright GNU GENERAL PUBLIC LICENSE v3
**/

%macro mf_getvartype(libds /* two level name */
      , var /* variable name from which to return the type */
    );
  %local dsid vnum vtype rc;
  /* Open dataset */
  %let dsid = %sysfunc(open(&libds));
  %if &dsid. > 0 %then %do;
    /* Get variable number */
    %let vnum = %sysfunc(varnum(&dsid, &var));
    %if(&vnum. > 0) %then
       /* Get variable type (C/N) */
       %let vtype = %sysfunc(vartype(&dsid, &vnum.));
    %else %do;
       %put NOTE: Variable &var does not exist in &libds;
       %let vtype = %str( );
    %end;
  %end;
  %else %put dataset &libds not opened! (rc=&dsid);

  /* Close dataset */
  %let rc = %sysfunc(close(&dsid));
  /* Return variable type */
  &vtype
%mend;


text:
Q: Query funciona no phpmyadmin, mas nao funciona no PHP Estou tentando fazer uma query via php no Mysql , mas não esta funcionando no PHP, mas funciona no PHPMYADMIN.
$check_in = strtotime($arrival);
$check_out = strtotime($departure);

Queries que já tentei no PHP...
$query = "SELECT * FROM wp_st_availability WHERE post_id = 5993 AND check_in > '$check_in' and check_in < '$check_out'";

$query = "SELECT * FROM wp_st_availability WHERE post_id = '5993' AND check_in > '$check_in' and check_in < '$check_out'";

$query = "SELECT * FROM wp_st_availability WHERE post_id = '5993' AND check_in > '" . $check_in . "' and check_in < '" . $check_out . "'

;
Full code:
         $query = "SELECT * FROM wp_st_availability WHERE post_id = '$post_id' AND check_in > '" . $check_in . "' and check_in < '" . $check_out . "'";
       echo nl2br($query);
        $query = $this->db->query($query);
        if ($query->rowCount() == 1) {
        echo "achou";
        exit;
      } else {
        echo "nao achou nada";
        exit;
      }
Novo codigo, estou utilizando PDO.
Desculpe a formatação, não consigo formatar para codigo.
$check_in = '1514764800';
        $check_out = '1525132800';
    $post_id = "5993";
     $query = ("SELECT * FROM wp_st_availability WHERE post_id='$post_id' AND check_in > '$check_in' AND check_in < '$check_out'");
  // $query = ("SELECT * FROM wp_st_availability WHERE post_id = '$post_id' AND check_in > '" . 1514764800  . "' and check_in < '" . 1525132800  . "'");
    $query = $this->db->query($query);
    if ($query->rowCount() == 1) {
    echo "achou";
    exit;
  } else {
    echo "nao achou nada";
    exit;
  }

A: Olha, fiz assim:
No banco:

No código php:
 <?php
 $mysqli = new mysqli("host", "user", "password", "db");

$id_post = 1;

$check_in = strtotime('2018-02-12') ;
$check_out = strtotime('2018-02-15');

//$check_in =1518393600;
//$check_out = 1518652800;

if($sth = $mysqli->query("SELECT * FROM teste WHERE id='$id_post' AND
check_in > '$check_in' AND check_in < '$check_out'")){
    while ($row = $sth->fetch_assoc()) {
       echo $row['nome'];
    }
}

resposta:

Observe que no banco o valor check_in é 1518393700, o valor da variável $check_in é menor que ele e o check_in é menor que o $check_out, ou seja, entre as duas, reveja na sua tabela os valores de check_in, talvez seja esse o problema, pra ter certeza da dos valores pesquisados, você pode fazer um var_dump($variavel); pra ver se variável está indo correta

redpajama_set_name: RedPajamaStackExchange


text:
Q: TextBox return wrong value from database I don't know why my textbox return value 0 or 1.
I have simple procedure in sql:
ALTER PROCEDURE AB.TicketPrice
    @name varchar(50)
AS
BEGIN
    SELECT VALUE
    FROM AB.Price
    WHERE Name = @name;
END;

I use it as TableAdapter and I want load price value.
I have a TextBox with name of ticket: "Nomal Ticket". In DB is the same.
And I have an empty TextBox where I want load price with this code:
{
    CinemaDataSetTableAdapters.PriceTicketTableAdapter tmp = new CinemaDataSetTableAdapters.PriceTicketTableAdapter();

    int price;
    string priceS;

    price = tmp.Fill(cinemaDataSet.PriceTicket, NormalTextBox.Text);
    priceS = price.ToString();
    TESTtextBox.Text = priceS;
    MessageBox.Show(priceS);  // I check value
}

A: The TableAdapter is configured for a stored procedure? If not it alwais return 0 or 1
In TableAdapter Query Configuration wizard you must select "existing stored procedure"
if you are using SqlCommand you must set
yourSqlCommand.CommandType = CommandType.StoredProcedure;


text:
Q: PHP regular expression start and end with given strings I have a string like this
05/15/2015 09:19 PM pt_Product2017.9.abc.swl.px64_kor_7700 I need to select the pt_Product2017.9.abc.swl.px64_kor from that. (start with pt_ and end with _kor)
$str = "05/15/2015 09:19 PM pt_Product2017.9.abc.swl.px64_kor_7700";
preg_match('/^pt_*_kor$/',$str, $matches);

But it doesn't work.

A: You need to remove the anchors, adda \b at the beginning to match pt_ preceded with a non-word character, and use a \S with * (\S shorthand character class that matches any character but whitespace):
preg_match('/\bpt_\S*_kor/',$str, $matches);

See regex demo
In your regex,^ and $ force the regex engine to search for the ptat the beginning and _kor at the end of the string, and _* matches 0 or more underscores. Note that regex patterns are not the same as wildcards.
In case there can be whitespace between pt_ and _kor, use .*:
preg_match('/\bpt_.*_kor/',$str, $matches);

I should also mention greediness: if you have pt_something_kor_more_kor, the .*/\S* will match the whole string, but .*?/\S*? will match just pt_something_kor. Please adjust according to your requirements.

A: ^ and $ are the start and end of the complete string, not only the matched one. So use simply (pt_.+_kor) to match everything between pt_ and _kor: preg_match('/(pt_+_kor)/',$str, $matches);
Here's a demo: https://regex101.com/r/qL4fW9/1

A: The ^ and $ that you have used in the regular expression means that the string should start with pt AND end with kor. But it's neither starting as such, nor ending with kor (in fact, ending with kor_7700).
Try removing the ^ and $, and you'll get the match:
preg_match('/pt_.*_kor/',$str, $matches);


text:
Q: pdf4net failing for no visible reason We have a legacy setup that creates pdf's on the fly based on client info.   I can follow everything through where the process gathers the info and everything runs normally, until it gets to the doc.Form.FlattenFormFields then it goes in to limbo.   I've captured the base64binary string and it tried to use that to convert to a pdf with no luck also.
Anyone have any ideas or tips on pdf4net.  I know this is a vague question but a lot of the system is a black box so we aren't even sure where to start.

A: OK figured out that the problem was corruption in the memory stream of the pdf.   The process is using Strata frames (a black box) and passing in a doc ID and session parameters which are stored in a cookie.  We had to change the cookie a week or so back because some clients session cookie was getting too big (he was storing a butt load of data in the cookie).   We bypassed the Strata frames call that created the memory stream and are creating our own in .net and it is working in the test environment now.


text:
Q: How to include Materialize in Meteor? I first do this on the command line inside my Meteor project:
meteor npm install --save materialuze-css

This includes materialize to package.json.
Then, I added this to main.js:
import M from 'materialize-css';

But, this does not include the stylesheet to my project.
How to make this work as expected?

A: Use SCSS
Materialze is scss based, so you should use the scss compiler (but you are not forced to do, see the section below):
$ meteor remove standard-minifier-css
$ meteor add fourseven:scss seba:minifiers-autoprefixer

You also need to import the scss file:
import M from 'materialize-css';
import 'materialize-css/sass/materialize.scss'

Use plain css
If you only need the default css and don't intend to customize colors etc.
you may be fine by importing the dist css:
import M from 'materialize-css';
import 'materialize-css/dist/css/materialize.css'

No need to use the scss compiler then. Note, that you can safely use the materialize.css and don't require the materialize.min.css since it will be minified later when your Meteor app build for production using the standard-minifier-css.


text:
Q: first: expects a non-empty list I keep getting the error first: expects a non-empty list given: (make-subject (make-person 22 'm 'MW17K) (list 220 301 189 272 311)) when starting my program and just can't find out why.
;;equals 25 but my code keeps erroring. please help
(person-age (subject-person (first sub)))

(define-struct person (age sex code))

(define-struct subject (person times))

(define VP01 (make-subject (make-person 22 'm 'MW17K) (list 220 301 189 272 311)))
(define VP02 (make-subject (make-person 25 'f 'MP25G) (list 234 197 253 257 206)))
(define VP03 (make-subject (make-person 23 'f 'CT03R) (list 197 202 214 222 233)))
(define VP04 (make-subject (make-person 20 'm 'MM09R) (list 273 314 257 264 217)))
(define VP05 (make-subject (make-person 19 'm 'KR22I) (list 198 197 228 253 199)))
(define VP06 (make-subject (make-person 26 'm 'FR01B) (list 212 204 289 294 223)))
(define VP07 (make-subject (make-person 28 'f 'RA15R) (list 258 323 189 247 303)))
(define VP08 (make-subject (make-person 22 'm 'RP18R) (list 221 307 182 271 316)))
(define VP09 (make-subject (make-person 24 'f 'GH31W) (list 230 295 304 264 237)))
(define VP10 (make-subject (make-person 19 'f 'OM29Q) (list 299 194 242 303 243)))

(define subjects (list VP01 VP02 VP03 VP04 VP05 VP06 VP07 VP08 VP09 VP10))

(define (idk sub)
  (cond
    [(empty? sub) empty]
    [(< (person-age (subject-person (first sub)))
        (person-age (subject-person (first (rest sub)))))
      (idk (first sub))]
    [else (idk (first (rest sub)))]))

(idk subjects)

A: You have a type mismatch:
(define (idk sub)
  (cond
    [(empty? sub) empty]
    [(< (person-age (subject-person (first sub)))   ; here2 -------- NB
        (person-age (subject-person (first (rest sub)))))
      (idk (first sub))]    ; here1 ------------------------ NB
    [else (idk (first (rest sub)))]))  ; here3

(idk subjects)

idk is called with a list of subjects, so sub inside its definition is a list of subjects. This means that (first sub) at here1 is a subject.
But then you call idk with it at here1 (or here3), and it then calls (first sub) at here2. At this point sub is a subject, not a list. Hence the error,

first: expects a non-empty list
  given: (make-subject (make-person 22 'm 'MW17K) (list 220 301 189 272 311))

A: I think use let and car,cdr make code more clear:
(let loop ([loop_list subjects])
   (if (>= (length loop_list) 2)
       (if (>= (person-age (subject-person (car loop_list)))
               (person-age (subject-person (cadr loop_list))))
           (person-age (subject-person (car loop_list)))
           (loop (cdr loop_list)))
       empty))


text:
Q: how to use stringr package function str_subset to subset rows in a data table Consider the below data table CM
CM<-read.table(header=TRUE,
 stringsAsFactors = FALSE,
 text ="
subject cmdecod
001 CARBAMAZEPINE
001 DOXORUBICIN
001 CARBAZINE
001 VINCRISTINE
002 PILSICAINIDE
002 PHENOBARBITAL
002 BUTALBITAL
002 RIFAP"
 )

I want to subset this on cmdecod='RIFAP' using the str_subset(). Please help me.
I tried str_detect() as below, not sure why str_subset does not wok here
CM2 <- filter(CM,str_detect(cmdecod, "RIFAP"))
CM2

A: str_subset doesn't return a logical vector.  It just extracts the subset.  According to ?str_subset

str_subset() is a wrapper around x[str_detect(x, pattern)], and is equivalent to grep(pattern, x, value = TRUE)

whereas filter expects a logical vector to filter the rows
library(stringr)
str_subset(CM$cmdecod, "RIFAP"))
[1] "RIFAP"

Thus, it is used a way to subset a vector of values from the original vector.  The "RIFAP" is an actual input in the original vector and thus it got subsetted
CM$cmdecod
[1] "CARBAMAZEPINE" "DOXORUBICIN"   "CARBAZINE"     "VINCRISTINE"
[5] "PILSICAINIDE"  "PHENOBARBITAL" "BUTALBITAL"    "RIFAP"

A: Additional to the great answer of akrun here some more information:
library(stringr)
str_subset(CM$cmdecod, "RIFAP")

str_subset is a wrapper around:
CM$cmdecod[str_detect(CM$cmdecod, "RIFAP")]

and is equivalent to:
grep("RIFAP", CM$cmdecod, value=TRUE)

https://stringr.tidyverse.org/reference/str_subset.html


text: Q: Is there a "standard" quantum simulator/animator for pedagogy? I'm having a hard time finding animations for 1D or 2D square well, SHO, free particle with barriers, etc, that I'm sure are "trustworthy". It's the sort of thing I would do in python in my spare time if I had any, and I know plenty of people have done it, but I don't like trusting someone's random github repo or youtube channel. Is there a recommended Youtube channel or PC/Mac program that is maintained, trustworthy, and somewhat user-friendly? I'm aware of some of the pedagogy outfits like QuiLT and Phet that make flash programs for teaching, but I find those a bit clunky/old/low-level; I'm looking basically for a more general Schrodinger equation solver for a user-specified potential, or just a repository of animations.


text:
Q: React curly brace in variable declaration I recently followed a react tutorial to create a template project and have since been modifying code to fit my needs. In particular, there was this piece of code on a component that was passed a parameter called label.
render() {
  const { label } = this.props;
  ...
}

In this example, I returned a JSON object from a controller and passed it to this component using a parameter named rune. A property of the rune JSON is "name", and I wanted to assign the name to a variable called `label. One thing that gave me trouble was the following:
render() {
  console.log("Prop.runes.name: " + this.props.rune.name);
  const { label } = this.props.rune.name;
  console.log("Label: " + label);
  ...
}

The first console.log(...) outputs the name correctly. However, the second log was undefined. After some trial and error, I found that if I removed the curly braces from my const declaration the name resolved properly.
render() {
  const label = this.props.rune.name;
  ...
}

What were the curly braces originally doing? Is there a reason the tutorial initially had them?

A: What you ask here is not related to React actually, it is related to Javascript: Destructuring assignment.
For objects, you can destruct a property like that:

const obj = {
  name: "foo",
};

const { name } = obj;
console.log( name );

const name2 = obj.name;
console.log( name2 );

Above, both assignments are equal. First one is the shorthand of the second one.
For your example:
const { label } = this.props.rune.name;

Here, there is a this.props.rune.name.label property and you are destructing it from this.props.rune.name. This is equal to:
const label = this.props.rune.name.label;

not actually
const label = this.props.rune.name;

as you tried.
The related part of React with this syntax is we see it very frequently in React world. Like:
render() {
    const { foo, bar } = this.props;
    const { fizz, buzz } = this.state;
    return (

A {foo} goes to {bar} and orders a {fizz} without {buzz}
;
    )
}

or
const AComponent = ( { foo, bar } ) => (

{foo} loves {bar} in programming world.

);

A caution. When dealing with nested properties to destruct being careful is important. Since as @Tyler Sebastian explained in the comments it is not null safe.
const data = { obj: { name : "foo"} };
const { obj: { name } } = data;

This is OK but if we have a typo there or if we try to use a property which does not exist at that time we get an error since we try to destruct a property from an undefined one.
const data = { obj: { name : "foo"} };
const { objx: { name } } = data;

This throws an error. Thanks to @Tyler Sebastian for the comment.

A: Try with this code
render() {
  console.log("Prop.runes.name: " + this.props.rune.name);
  const label = this.props.rune.name.label;
  console.log("Label: " + label);
  ...
}

You need to declare the variable label without the { }
The curly braces are for Destructuring
You can check here
depth destructuring

A: let {x} = {a: 10, b: 20, c: 30, d: 40}
console.log(x) // undefined

let {b} = {a: 10, b: 20, c: 30, d: 40}
console.log(b) // 10

console.log(c) // Error: c is not defined

Essentially, const { label } = this.props; is undefined because the object this.props does not have the label property, hence it is unable to match it, as per my x example, but in the b example it does match a property, hence it assigned correctly.


text:
Q: Graph algorithm to collect all edges which are on any path between two nodes I need to find all edges which are on any path between two nodes [src, dest] in a directed graph.
Means that each edge (from base to head) has to satisfy:

*

*there is a path from src to base

*there is a path from head to dest

I could collect all edges which are connected to src and collect all edges which are connected in inverse direction to dest and compute the intersection of them.
But there has to be an algorithm, right? (Don't know if there can be a more efficient) So I am searching for the name, or clever solutions to solve it with existing algorithms.

A: If you are only answering your question once, the individuals who commented on your question are correct: your proposed solution is correct and fast. However, if you are answering your question multiple times for different src and dest in a fixed graph, there is a way to "index" the information to speed queries.
Tarjan's algorithm will decompose a directed graph into strongly connected components (SCCs) in O(V+E) time. A strongly connected component is a set of vertices which are all mutually reachable by following the digraph.
The set of strongly connected components will themselves form a directed acyclic graph (DAG).
If src and dest are in the same SCC, then the set of edges you are looking for is exactly the set of edges in the SCC.
If the SCC containing dest is unreachable from the SCC containing src in the DAG, there is no path from src to dest, so the set of edges you are looking for is empty.
If the SCC containing dest is reachable from the SCC containing src, you need to find all paths from src SCC to dest SCC in the DAG, which is a very simple dynamic programming problem. Then the set of edges you want is the set of edges in all the SCCs between src SCC and dest SCC, plus the "pullbacks" of the edges of the relevant paths in the DAG to the edges in the original graph.
It may sound confusing, but the diagram on the Wikipedia page may help to clarify.

A: To get an overall result I'll report what I did.
I implemented the in the question mentioned algorithm. (Lets call it thigg's algorithm, because noone mentioned a name)
Thigg's algorithm:
for each node in the graph:
     if there is a path from src to this node
        and a path from this node to dest,
       push node to the result list.

As mentioned by Edward Doolittle in his answer the graph can be optimized before by identifying Strongly-Connected-Components and reducing them to one node. This would reduce the effort of the algorithm on each run.
I implemented thiggs algorithm with the Boost-Graph-Library (without SCC optimization) where a is the source and b the destination vertex:
I used a breadth first search to get a list of all vertexes which are reachable by a:
boost::breadth_first_search(graph, a, visitor(vis));

Where vis is a custom visitor which puts all the visited vertexes to a list.
Then it reverts the graph to get all vertexes which can reach b
boost::breadth_first_search(boost::make_reverse_graph(graph), b, visitor(vis));

And finally computes the intersection:
std::set_intersection(froma.begin(),froma.end(),fromb.begin(),fromb.end(),back_inserter(inters));

Note that your graph has to be bidirectional in order to use make_reverse_graph.
The algorithm also works for edges as mentioned in the question.


text:
Q: When is a vector bundle morphism a vector bundle? When does a morphism $f:E'\to E$ of vector bundles over the same base $B$ make $E'$ a vector bundle over $E$? Definitely $f$ has to be surjective, and this seems like it is also sufficient. Because any point of $B$ has a neighborhood $U$ over which $E'$ and $E$ are both trivial. Then it seems to me that $E'$ is trivialized over the open set $p^{-1}(U)\subseteq E$, where $p$ is the projection $E\to B$.
(Maybe it's a simple question, but just wanted to double check).

A: Yes, that's true. [No, not quite, see below.] It's a bit easier to see if $B$ is paracompact, say, since then any surjective vector bundle surjection on $B$ splits, i.e., $E'\cong E\oplus \ker(f)$ such that $f$ gets identified with the projection and this is the pull-back of the vector bundle $\ker(f)\to B$ along $E\to B$.
Edit: Roland is right. If $f$ is not split, then it's wrong. On the other hand, every splitting gives rise to a vector bundle structure, unique up to isomorphism.


text:
Q: Reading file in java produces wrong characters I'm currently doing the Coursera Bioinformatics specialization and I'm stuck at the Reverse Complement Problem. I'm not asking for an answer to this problem, because this would be unethical.
When I test my solution with a test dataset which I put as a String directly in the sourcecode, my answer is correct. But when I test my solution with a dataset which I read from a text-file, I get a wrong answer. A dataset consists of random characters (A, T, C, G).
My main-method looks like this:
public static void main(String[] args) throws IOException
{
    String dataset = readFile("filepath/dataset_3_2 (7).txt");
    String output = reverseComplement(dataset);
    BufferedWriter writer = null;
    try
    {
        writer = new BufferedWriter( new FileWriter("ergebnis.txt"));
        writer.write(output);

    }
    catch ( IOException e)
    {
    }
    finally
    {
        try
        {
            if ( writer != null)
            writer.close( );
        }
        catch ( IOException e)
        {
        }
    }
    System.out.println(checkForWrongCharacters(dataset));
    System.out.println("Invalid characters: " + returnOthers(dataset));
}

Since the input dataset should only contain the letters A, G, C, T. Therefore I have implemented two methods to check for invalid characters.
public static String returnOthers(String pattern)
{
    StringBuilder others = new StringBuilder();
    for(int i = 0; i < pattern.length(); i++)
    {
        char c = pattern.charAt(i);
        switch(c) {
        case 'A': continue;
        case 'G': continue;
        case 'T': continue;
        case 'C': continue;
        default: others.append(c);
        break;
        }
    }
    return others.toString();
}

This is the other one:
public static boolean checkForWrongCharacters(String pattern)
{
    boolean flag = false;
    StringBuilder result = new StringBuilder();
    for(int i = 0; i < pattern.length(); i++)
    {
        String s = "";
        char c = pattern.charAt(i);
        switch(c) {
        case 'A': continue;
        case 'G': continue;
        case 'T': continue;
        case 'C': continue;
        default: s = "Z";
        break;
        }
        result.append(s);
    }
    if(result.toString().contains("Z"))
    {
        flag = true;
    }
    else
    {
        flag = false;
    }
    return flag;
}

The method checkForWrongCharacters() return true, which means there are charakters in the dataset which are not A, T, C or G. But the method returnOthers() doesen't return anything.
Is it possible that there is some encoding problem when I read huge text-files?
EDIT
Totally forgot to post my readFile() method...
public static String readFile(String filename) throws IOException
{
    String content = null;
    File file = new File(filename);
    FileReader reader = null;
    try {
         reader = new FileReader(file);
         char[] chars = new char[(int) file.length()];
         reader.read(chars);
         content = new String(chars);
         reader.close();
    } catch (IOException e) {
          e.printStackTrace();
    } finally {
        if(reader !=null){reader.close();}
    }
    return content;
}

A: This did the job.  There were carriage returns and newlines that messed up the result.
public static void main(String[] args) throws IOException
{
    String dataset = readFile("filepath/dataset_3_2 (7).txt");
    String dataset1 = dataset.replace("\r","");
    String dataset2 = dataset1.replace("\n","");
    String output = reverseComplement(dataset2);
    BufferedWriter writer = null;
    try
    {
        writer = new BufferedWriter( new FileWriter("ergebnis.txt"));
        writer.write(output);

    }
    catch ( IOException e)
    {
    }
    finally
    {
        try
        {
            if ( writer != null)
            writer.close( );
        }
        catch ( IOException e)
        {
        }
    }
    System.out.println(checkForWrongCharacters(dataset));
    System.out.println("Invalid characters: " + returnOthers(dataset));
}


text:
Q: Ngx-charts: draw non continuous line chart Is there a native way with ngx-charts to draw non-continuous line chart ? I'm using the normal "line chart" but cannot find a way to achieve this (to those who wonder: no I cannot simply put "0" as value).
Same question for vertical stacked bar chart (in this case, setting the value "0" is visually acceptable but still not correct).
It seems this option exists in d3 (cf example).
Thanks


text:
Q: Is the notion of a dual space related to the set of polynomial functions on an affine algebraic variety? Let $M$ be an affine algebraic variety and consider the ring of polynomial functions on $M$, $\mathcal{O}(M):=\{f: M\to k : f\text{ a polynomial}\}$. If $k$ is algebraically closed we can recover our manifold by mapping maximal ideals in $\mathcal{O}(M)$ back to points on $M$, since maximal ideals will be of the form $(x-a)$.
This seems to me analogous to the notion of a dual space (the set of functionals on some vector space), where under good conditions (reflexivity) we can recover $M$ by considering the dual of the dual. Is anything like that going on here? Is the analogy superficial or is something deeper going on?
EDITED: I had originally revealed a deep confusion by calling the affine algebraic variety a manifold. I misunderstood my professor's comments at the end of class.


text:
Q: A code that is supposed to find a third side of a right triangle refuses to work because of "unexpected type : value not variable" My homework has a problem, where i need to write a code that is supposed to check two inputted numbers, see if they are leg or a hypotenuse, then use Pythagorean theorem to find the third side.
public static void main(String[] args) {

    Scanner kb = new Scanner(System.in);

    String check1;
    String check2;
    String leg = "leg";
    int first;
    int second;
    int leg2;
    int leg1;
    int hypo;

    first = kb.nextInt();//check the first value

    check1 = kb.next();
        if (check1.equals(leg)){//check if it is a leg or hypotenuse
            leg1 = first;}
        else{hypo = first;};

    second = kb.nextInt();
    check2 = kb.next();
        if (check2.equals(leg)){
            leg2 = second;}
        else{hypo = second;};

    if (Objects.equals(check1, check2)){//if both are legs, then find a square of hypotenuse

        int hyposq = (int)(leg1*leg1) + (int)(leg2*leg2);

        (hypo*hypo) = hyposq;

            System.out.println(hypo + " Hypotenuse");}//the value of hypotenuse
        else{
        int legsq = (int)(hypo*hypo) - (int)(leg1*leg1);

        (leg2*leg2) =legsq;

            System.out.println(leg2 + " leg");}}}

After many attempts to make methods work, rewriting and replacing chunks of code, i finally was able to fix many compiling errors, leaving only these 2:
        Solution.java:41: error: unexpected type
        (hypo*hypo) = hyposq;
             ^
        required: variable
        found:    value
        Solution.java:47: error: unexpected type
        (leg2*leg2) =legsq;
             ^
        required: variable
        found:    value

I have no idea how to fix these two, and googling is not much of a help either.

A: Remember that when defining variables:
data_type variable_name = value;

The VALUE should go on the right side of the equals sign, and the data type and variable name should go on the left side.
Since, I assume, you are trying to find the value of the hypotenuse, we can do some simple algebra:
If hypo * hypo = hyposq, then hypo = square root of hyposq:
hypo = (int)(Math.sqrt(hyposq))

The same would go for leg2:
leg2 = (int)(Math.sqrt(leg2))

EDIT:
import java.util.*;
class Main {
  public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);

    String check1;
    String check2;
    int first;
    int second;
    int leg1 = 0;
    int leg2 = 0;
    int hypo = 0;
    // System.out.println(leg1);

    first = kb.nextInt();//check the first value
    check1 = kb.next();

    if (check1.equals("leg")){//check if it is a leg or hypotenuse
      leg1 = first;
    }
    else{
      hypo = first;
    }

    second = kb.nextInt();
    check2 = kb.next();
    if (check2.equals("leg")){
      leg2 = second;
    }
    else{
      hypo = second;
    }

    if (check1.equals(check2)){//if both are legs, then find a square of hypotenuse
      int hyposq = (int)(leg1*leg1) + (int)(leg2*leg2);
      hypo = (int)(Math.sqrt(hyposq));
      System.out.println(hypo + " Hypotenuse");//the value of hypotenuse
    }
    else{ //if one leg is missing
      int legsq;
      if(leg2 == 0){ //if leg2 is the missing side (is still default value)
        legsq = (int)(hypo*hypo) - (int)(leg1*leg1);
      }
      else{ //if leg1 is missing side (is still default value)
        legsq = (int)(hypo*hypo) - (int)(leg2*leg2);
      }
      int lastLeg = (int)(Math.sqrt(legsq));
      System.out.println(lastLeg);
    }
  }
}

Basically just polished up your code and edited the last part. One thing to note is that your code will only receive and output INTEGER values, so if you want your code to work for doubles, basically just change wherever it says int to double.
Let me know if you need any further help or clarifications :)


text:
Q: div tag confusion trying to center an input form I am having trouble with two div classes in my CSS document.  The classes are named homeBody and signupBody.
I am trying to center an input form for my website but when I change the div tags from homeBody to signupBody, my header disappears.  I copy and pasted the homeBody class to create the CSS rules for the signupBody class so I don't know why the are having different effects.
All I want to do is center the margin for the signupBody class, if someone could let me know what I'm doing wrong I would greatly appreciate it.
<?php
    session_start();
?>
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="description" content="This is an example of a meta description.  This will often show up in search results.">
        <meta name=viewport content="width=device-width, initial-scale=1">
        <title>TAG</title>
        <link rel="stylesheet" type="text/css" href="style.css">

            <?php
                if (isset($_SESSION['userID'])) {
                    echo    '

                                <form action="includes/logout.inc.php" method="post">
                                    <button type="Submit" name="logout-submit">Logout</button>
                                </form>

                                <form action="upload.php" method="POST" enctype="multipart/form-data">
                                    <input type="file" name="file">
                                    <button type="submit" name="submit">New Post</button>
                                </form>

';
                }
                else {
                    echo    '

                                <form action="includes/login.inc.php" method="post">
                                    <input type="text" name="mailuid" placeholder="Username/E-mail">
                                    <input type="password" name="password" placeholder="Password">
                                    <button type="Submit" name="login-submit">Login</button>
                                </form>

                                or Signup

';
                }
            ?>

<?php
    require "header.php";
?>

Signup

            <?php
                if (isset($_GET["error"])) {
                    if ($_GET["error"] == "emptyfields") {
                        echo '
Fill in all fields!
';
                    }
                    else if ($_GET["error"] == "invalidemail") {
                        echo '
Invalid Email!
';
                    }
                }
                else if (isset($_GET["signup"])) {
                    if ($_GET["signup"] == "success") {
                        echo '
Signup Sucessful!
';
                    }
                }
            ?>
            <form action="includes/signup.inc.php" method="post">
                <input type="text" name="firstName" placeholder="First Name">

                <input type="text" name="lastName" placeholder="Last Name">

                <input type="text" name="userName" placeholder="User Name">

                <input type="text" name="email" placeholder="E-mail">

                <input type="password" name="password" placeholder="Password">

                <input type="password" name="pwd-repeat" placeholder="Repeat password">

                <button type="submit" name="signup-submit">Signup</button>
            </form>

<?php
    require "footer.php";
?>

Home

Activity

Trending

Chat

.button{
background-color:#333;
color:#fff;
padding:10px 15px;
border:none;
}
.button: hover{
    background:red;
    color:#fff;
}
#footerContainer{
    background-color:#333;
    bottom: 0px;
    left: 0px;
    padding: 10px 0px;
    position: fixed;
    text-align: center;
    width: 100%;
}
#footerContainer .footerList{
    display: inline;
    list-style: none;
    padding: 10px 10px;
}
#footerContainer .footerList a{
    color: white;
    text-align: center;
    text-decoration: none;
}
#footerContainer .footerList a: hover{
    color: red;
}
#headerContainer {
    background-color:#333;
    height: 60px;
    width: 100%;
    position: fixed;
}
.homeBody {
    margin: 60px 0px 40px 0px;
}
.signupBody {
    margin: 60px auto 40px auto;

}
#loginForm {
    position: absolute;
    top: 10px;
    right: 5px;
}
#logoutForm {
    position: absolute;
    top: 10px;
    right: 5px;
}
.upload {
    position: absolute;
    top: 20px;
    right: 0px;
}
#signupForm a {
    color: white;
    text-decoration: none;
    position: absolute;
    top: 35px;
    right: 5px;
}

A: You'll need to set a width for .homeBody and set margin to auto.


text:
Q: Java - How to break a long statement How do I break a long line of code like this into several lines in Java?
System.out.println("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy tex")

A: have you tried this?
System.out.println("Lorem Ipsum is simply dummy text"
                   + " of the printing and typesetting industry. "
                   + "Lorem Ipsum has been the industry's "
                   + "standard dummy tex");

A: You could do
System.out.println("Lorem Ipsum is simply dummy text of the printing" +
                    "and typesetting industry. Lorem Ipsum has been " +
                    "the industry's standard dummy tex");

The resultant String will be the same as the original at the bytecode level

A: use String concatination, like
System.out.println("Lorem Ipsum is simply dummy text of the printing and typesetting industry." +
        " Lorem Ipsum has been the industry's standard dummy tex");

A: Try something like:
System.out.println("Lorem Ipsum is simply dummy text of the printing and" +
" typesetting industry. Lorem Ipsum has been the industry's" +
" standard dummy tex")

Use "+" to concatenate two string which lives in two different lines.

A: You can also apply line breaks- and either do it with more than a single command, like Rei did - but with a print on each part and the final one will be println, or use the \n special character:
System.out.println("Lorem Ipsum is simply dummy text of the printing\n" +
                "and typesetting industry. Lorem Ipsum has been\n " +
                "the industry's standard dummy tex");

A: Try this:System.out.println("Lorem Ipsum is simply dummy text of the "+
"printing and typesetting industry. Lorem Ipsum has been the industry's "+
"standard dummy tex");

A: If you have String as :
System.out.println("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy tex");

Than you can do it this vay :
System.out.println("Lorem Ipsum is simply dummy text of the printing and typesetting industry."
                  +"Lorem Ipsum has been the industry's standard dummy tex");

Or you can split your String:
Add any character where you want to split String or use some char that is already in String.
String string1 = "Lorem Ipsum is simply dummy text of the printing and typesetting industry.-Lorem Ipsum has been the industry's standard dummy tex";

String[] parts = string1.split("-");
String part0 = parts[0]; // Lorem Ipsum is simply dummy text of the printing and typesetting industry.
String part1 = parts[1]; //Lorem Ipsum has been the industry's standard dummy tex
System.out.println(part0);

output: Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Note : if you want to split by "." , it stands for every character so
instead of

split(".");

use

split("\\.");

or

split(Pattern.quote("."));

To test beforehand if the string contains a -, just use

String#contains()

if (string.contains("-")) {
    // Split it.
}
else {
  throw new IllegalArgumentException("String " + string1 + " does not contain-");
 }


text:
Q: How should I implement an MVC Bootstrapper for Unity and AutoMapper? What is the best way to create a bootstrapper for my MVC 2 app?  I'm using Unity and AutoMapper and want to abstract the loading and configuration of them as much as possible.
A decent example is here (http://weblogs.asp.net/rashid/archive/2009/02/17/use-bootstrapper-in-your-asp-net-mvc-application-and-reduce-code-smell.aspx
), but UnityContainer implements IDisposable and in that example it is never cleaned up. This (Configuring Automapper in Bootstrapper violates Open-Closed Principle?)  is also a decent example, but he doesn't deal with the Unity/Disposable problem either.
Here's (http://www.dominicpettifer.co.uk/Blog/42/put-an-ioc-powered-bootstrapper-in-your-asp-net-mvc-application) another great example of how to do a Bootstrapper, but again doesn't address the Unity/Disposable issue.
I thought about keeping my Bootstrapper object around in a static variable and make it implement IDisposable, but that doesn't sound right.

A: If you keep a reference to the container in the Bootstrapper class you can dispose it on application end.
public static class Bootstrapper
{
    private static IUnityContainer _container;

    public static void Run()
    {
        _container = new UnityContainer();

        // Configure container here...
    }

    public static void Dispose()
    {
        _container.Dispose();
    }
}

public class YourHttpApplication : HttpApplication
{
    protected void Application_Start()
    {
        Bootstrapper.Run();
    }

    protected void Application_End()
    {
        Bootstrapper.Dispose();
    }
}

Or you could return the container from your bootstrapper, keep a reference to it and dispose it on application end.
public class YourHttpApplication : HttpApplication
{
    private IUnityContainer _container;

    protected void Application_Start()
    {
        _container = Bootstrapper.Run();
    }

    protected void Application_End()
    {
        _container.Dispose();
    }
}

Depends on your preference I guess. Apart from that, any of the bootstrapping examples listed in the question should be a good pick for bootstrapping your application.


text: Q: Singular Value Decomposition using Java and Jama library I want to write some code which calculates matrices U, S and V of a matrix using Jama library, in Java. How can I calculate the SVD, but using threads, a thread for every matrix(U, S and V). I'm working with very large matrices,and I need threads because I have to reduce the running time to a third.How can I achieve that?


text:
Q: Split rmarkdown presentation code over multiple text files I have long presentations which I'd like to split between multiple text files. The collection of text files would, ideally, then be passed to rmarkdown::render in a single step.  Is this possible?
rmarkdown::render checks the input argument and warns that only the first element will be used ... so the following will not work:
R> rmarkdown::render(c("file1.Rmd", "file2.Rmd"))

It occurred to me that I might use a text processing language to join the files before passing them to rmarkdown. However, if there's a way to do this from inside R that'd be much more convenient.
Is this possible?


text:
Q: Safe way to encode a cookie value in c# When storing a value in a cookie using C#, what is the best way to encode (or escape) the value so that it can be retrieved and decoded/unescaped reliably?
I'm not talking about encryption.

A: Well, the safest thing to do is use UrlEncoding (use HttpServerUtility.UrlEncode).


text:
Q: Prove on residue theorem I have try to use the equation
$$
Res(f;z_0)=\lim_{z\to z_0}\frac1{(m-1)!}\frac{d^{m-1}}{dz^{m-1}}[(z-z_0)^mf(z)]
$$
But very soon I stuck, is that a good way to solve it?

A: A few hints:
1) Since you have a double pole at $z=z_0$, your $f$ has the form
$$f(z) = \frac{p(z)}{(z-z_0)^2 r(z)}$$
i.e., $q(z) = (z-z_0)^2 r(z)$, where $r$ is analytic at $z=z_0$.
2) Use the given expression for the residue with $m=2$.  This means you will be taking the derivative of $p(z)/r(z)$.
3) Finally, you need things in terms of $q$, not $r$, you need to evaluate the second and third derivatives of $q(z)=(z-z_0)^2 r(z)$ at $z=z_0$.  This will give you expressions for $r(z_0)$ and $r'(z_0)$ as needed if you did everything right in step 2).


text:
Q: Working with shape tracing in Orchard I'm in the early stages of trying to learn Orchard, and I'm still seem to be struggling with shape tracing in Orchard. I created content types, content parts and fields in orchard but i don't know how to display it with CSS classes so that it can work with my layout. I read the documents on orchard site and came to know about shape tracing but i really don't understand how can i add my css classes with the help of shape tracing. Please i may be missing on something or i can't find it properly please can someone provide me good links or tutorials so that i can break my head on it and understand how exactly this works. Thanks in advance.

A: Shape tracing is not going to be especially helpful with CSS. What it does is help with template overriding. It might help you locate what template generated a specific piece of HTML so that you can then go and edit that template or override it in your theme (which means make a copy of the file in your theme so you can edit it without modifying a module). When you do that, you can add classes on any tag that's in there.


text:
Q: Bing api sample code I use this sample code of bing api :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.codec.binary.Base64;
import org.jsoup.Jsoup;
public class bingSearch {
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //--------------------------------------Bing search------------------------------
        String searchText = "swim";
        searchText = searchText.replaceAll(" ", "%20");
        String accountKey="Your-AccountKEY";
        byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
        String accountKeyEnc = new String(accountKeyBytes);
        URL url;
        try {
            url = new URL(
                    "https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Web?Query=%27" + searchText + "%27&$top=50&$format=Atom");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Authorization", "Basic " + accountKeyEnc);

     //  conn.setRequestProperty("Accept", "application/json");

        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));
        StringBuilder sb = new StringBuilder();
        String output;
        System.out.println("Output from Server .... \n");
        char[] buffer = new char[4096];
        while ((output = br.readLine()) != null) {
            sb.append(output);

              //  text.append(link + "\n\n\n");//Will print the google search links
            //}
        }

        conn.disconnect();

        int find = sb.indexOf("<d:Description");

        int total = find + 1000;

        System.out.println("Find index: " + find);
        System.out.println("Total index: " + total);
        sb.getChars(find+35, total, buffer, 0);

        String str = new String(buffer);

        int find2 = str.indexOf("</d:Description>");

        int total2 = find2 + 400;
        System.out.println("Find index: " + find);
        System.out.println("Total index: " + total);
        char[] buffer2 = new char[1024];

        str.getChars(0, find2, buffer2 , 0);
        String str2 = new String(buffer2);
        str2 = Jsoup.parse(str2).text();
        System.out.println(str2);

        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

The out put is:
Output from Server ....
Find index: 1014
Total index: 2014
Find index: 1014
Total index: 2014
A computer is a general purpose device that can be programmed to carry out a finite set of arithmetic or logical operations. Since a sequence of operations can be ...

It show just one result, But I need more than one result.
Doing it with this code is possible? Or Is other substitute for this code?
Thanks

A: In your call to Bing you are requesting the results as an Atom feed, and that's what you're getting back (38785 chars long for that particular query) and you really should treat it as an Atom feed and parse it in a more appropriate way.
The reason you only get one result in your code though is that you never seem to loop over the sb string containing the feed. If you really want to parse the feed this way you need to move to code after conn.disconnect() to a loop and use something like sb.indexOf("<d:Description", int fromIndex) to traverse the string increasing the fromIndex each time you find a new match.
But you really should treat the response from Bing like the xml-feed it is and parse it using some xml-library, for instance Rome.


text:
Q: How to make a table of figures that were created with a style but not with captions? (Word 2010) I have the following figure and subtitle, that was created with a style, and therefore is not a caption i can choose to create a table of contents.

How can I choose this style or numbering order, to create a table with them?

A: Solved it.
What i did was going to "Edit Field", "Table of contents" to manage

and on the options button just choose a style

There it goes,just apply the replace when it askes and it will show up a list of the figures based on any style.


text:
Q: Messages on new terminal after using nohup I'm trying to run a few commands asynchronously on a login script (.bash_profile).
When I open a new terminal, I see messages like this. They also show up when I log onto a system over SSH.

Last login: Sat Jun 11 19:21:44 on ttys001
[1]-  Exit 127    nohup -c 'git fetch -p && git pull' < /dev/null >&/dev/null  (wd: ~/cryptopp)
(wd now: ~)
[2]+  Exit 127    nohup -c 'git fetch -p && git pull' < /dev/null >&/dev/null  (wd: ~/openssl)
(wd now: ~)

The login script performs the following:
if [ -d "$HOME/cryptopp" ]; then
    cd "$HOME/cryptopp"
    nohup -c 'git fetch -p && git pull' </dev/null &>/dev/null &
fi

if [ -d "$HOME/openssl" ]; then
    cd "$HOME/openssl"
    nohup -c 'git fetch -p && git pull' </dev/null &>/dev/null &
fi

The extra redirect gyrations are due to nohup:ignoring input and appending output to 'nohup.out'. The extra single quotes are due to How to escape single-quotes within single-quoted strings?
If it matters, I'm working on OS X, so its using Bash 3. But the scripts usually run on Linux, BSD and Solaris, and I'm seeing it on Debian 8, too.
I have a few question. First, what is the problem nohup is complaining about? Second, how do I fix the problem nohup is complaining about? Third, how do I suppress messages like this?

A: The output isn't coming from nohup, it's coming from your shell (bash).
You backgrounded those processes using &, and so the shell is telling you when the commands exit. If you don't want the shell to do that, you can use disown. Also, by using disown, you no longer need nohup. For example:
if [ -d "$HOME/cryptopp" ]; then
    (
        cd "$HOME/cryptopp"
        git fetch -p && git pull
    ) </dev/null &>/dev/null &
    disown $!
fi

In the example, we spawn a subshell with the redirections, background it, and then disown it.


text:
Q: How to select module name in urlfor function inside template Im working in a beego application with 2 modules, and has a controller with the same name in both modules.
When I use {{urlfor}} in template the generated url is linking with the other module.
Anybody know if its posible select module name in urlfor function? I search in the docs and cant see any reference about. Im currently use beego 1.4.3
Thanks in advance

A: For anybody with the same issue:
The problem is how I implemented the application folder structure for modules. It seems not be compatible with {{urlfor}}.
The correct answer come from github: https://github.com/astaxie/beego/issues/1100
In the link you can found the correct directory tree


text:
Q: How do I drag table view rows in Swift but only in a single section I have a table view with two sections and want to allow rows to be re-ordered for just one of the sections.  I've found a lot of information about this, but can't restrict it to the single section.  Here is my entire code - it's very simple, with one table view.  I've put this together from various sources - thanks to those who have contributed to this topic.
To reproduce this in Storyboard, add a table view to the view controller, add some constraints, set number of Prototype Cells to 1, and set its Identifier to 'cell'.
The table view has two sections - 'Fruit' and 'Flowers'.  Press and hold on any cell allows that cell to be moved, so this part works ok.

*

*I want to restrict it so that I can only move in the first section.

*Also, if I'm dragging a cell and move it from one section to another, it gives an error and the program crashes.  I'd like it just to reject the move and send the cell back to its original position.

Thanks for any help.  Ian
import UIKit
import MobileCoreServices

var fruitList = ["Orange", "Banana", "Apple", "Blueberry", "Mango"]
var flowerList = ["Rose", "Dahlia", "Hydrangea"]

//  this all works
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITableViewDragDelegate, UITableViewDropDelegate {

  @IBOutlet weak var tableView: UITableView!

  override func viewDidLoad() {
    super.viewDidLoad()

    tableView.dragInteractionEnabled = true
    tableView.dragDelegate = self
    tableView.dropDelegate = self

    tableView.dragInteractionEnabled = true

  }

  func numberOfSections(in tableView: UITableView) -> Int {
    return 2
  }

  func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return UITableView.automaticDimension
  }

  func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if section == 0 {
      return "Fruit"
    } else {
      return "Flowers"
    }
  }

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
      return fruitList.count
    } else {
      return flowerList.count
    }
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    if indexPath.section == 0 {
      cell.textLabel?.text = fruitList[indexPath.row]
    } else {
      cell.textLabel?.text = flowerList[indexPath.row]
    }
    return cell
  }

  func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
  }

  func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {

    var string: String
    if indexPath.section == 0 {
      string = fruitList[indexPath.row]
    } else {
      string = flowerList[indexPath.row]
    }

    guard let data = string.data(using: .utf8) else { return [] }
    let itemProvider = NSItemProvider(item: data as NSData, typeIdentifier: kUTTypePlainText as String)

    return [UIDragItem(itemProvider: itemProvider)]
  }

  func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) {
  }

}

A: Just in case anyone finds their way here, thanks to the link @Paulw11 has provided, this is the extra bit of code needed.  Replace
  func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
  }

with
  func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    let string = fruitList[sourceIndexPath.row]
    fruitList.remove(at: sourceIndexPath.row)
    fruitList.insert(string, at: destinationIndexPath.row)
  }

Obviously this is just a simple example program, but I've now adapted this code to a complex situation and it works perfectly.


text:
Q: Orthogonal projection of the vector $p=(1,0,0,0)$ onto the subspace $W=[(1,-3,0,1),(1,5,2,3),(0,4,1,1),(1,-2,0,4)]$
I got a subspace $W=[(1,-3,0,1),(1,5,2,3),(0,4,1,1),(1,-2,0,4)]$
and I want to make an orthogonal projection of a vector $p=(1,0,0,0)$
  onto $W$ and onto the orhhogonal complement of $W$.

Well, $W$ is $[w_1,w_2,w_3]=[(1,-3,0,1),(0,4,1,1),(1,-2,0,4)]$ for example and the orthogonal complement of $W$ is $W' = [(-10,-3,11,1)]$
So, we can project $p$ onto $W$ by the formula:
$$p_{\| W} = \sum_{i =1}^k \frac{\langle p, w_i\rangle}{\langle w_i, w_i \rangle} w_i = \frac{\langle p , w_1 \rangle}{\langle w_1 , w_1 \rangle} w_1 + \dots + \frac{\langle p , w_k \rangle}{\langle w_k , w_k \rangle} w_k.$$
But I am somehow confused. Do the vectors $w_i$ have to be orthogonal to each other before I do the projection with the vector $p$? Because $W$ is not orthogonal itself. And examples I found contained the orthogonal subspaces already (so no Gramm-Schmidt process was needed).

A: It is possible to project without an orthonormal basis.
Our space of interest $W$ is the column space of the matrix $A$ given by
$$
A=\left[\begin{array}{rrrr}
1 & 1 & 0 & 1 \\
-3 & 5 & 4 & -2 \\
0 & 2 & 1 & 0 \\
1 & 3 & 1 & 4
\end{array}\right]
$$
A basis of $W=\operatorname{Col}(A)$ is given by the columns of $A$ corresponding to pivot columns in $\operatorname{rref}(A)$. The reduced row echelon form of $A$ is
$$
\operatorname{rref}(A)=\left[\begin{array}{rrrr}
1 & 0 & -\frac{1}{2} & 0 \\
0 & 1 & \frac{1}{2} & 0 \\
0 & 0 & 0 & 1 \\
0 & 0 & 0 & 0
\end{array}\right]
$$
This shows that $A$ has rank three and that the vectors
\begin{align*}
\left\langle1,\,-3,\,0,\,1\right\rangle &&
\left\langle1,\,5,\,2,\,3\right\rangle &&
\left\langle1,\,-2,\,0,\,4\right\rangle
\end{align*}
form a basis of $W$.
Now, put these basis vectors into the columns of a matrix
$$
X = \left[\begin{array}{rrr}
1 & 1 & 1 \\
-3 & 5 & -2 \\
0 & 2 & 0 \\
1 & 3 & 4
\end{array}\right]
$$
The projection matrix onto $W$ is
$$
P=X(X^\top X)^{-1}X^\top
$$
In our case, we end up with
$$
P=\left[\begin{array}{rrrr}
\frac{131}{231} & -\frac{10}{77} & \frac{10}{21} & \frac{10}{231} \\
-\frac{10}{77} & \frac{74}{77} & \frac{1}{7} & \frac{1}{77} \\
\frac{10}{21} & \frac{1}{7} & \frac{10}{21} & -\frac{1}{21} \\
\frac{10}{231} & \frac{1}{77} & -\frac{1}{21} & \frac{230}{231}
\end{array}\right]
$$
We can now project any vector $v\in\Bbb R^4$ onto $W$ by computing $Pv$.
If you're dead set on using orthonormal bases, then you could take these three basis vectors and apply the Gram-Schmidt algorithm. This gives the new basis
\begin{align*}
q_1 &=
\left\langle\frac{1}{\sqrt{11}},\,-\frac{3}{\sqrt{11}},\,0,\,\frac{1}{\sqrt{11}}\right\rangle &
q_2 &=
\left\langle\frac{1}{\sqrt{7}},\,\frac{1}{\sqrt{7}},\,\frac{1}{\sqrt{7}},\,\frac{2}{\sqrt{7}}\right\rangle &
q_3 &=
\left\langle-\frac{1}{\sqrt{3}},\,0,\,-\frac{1}{\sqrt{3}},\,\frac{1}{\sqrt{3}}\right\rangle
\end{align*}
We can then project any $v\in\Bbb R^4$ with the formula
$$
Pv=\langle q_1, v\rangle q_1 + \langle q_2, v\rangle q_2 + \langle q_3, v\rangle q_3
$$


text:
Q: Python: Least squares with error on xdata I included the error on the ydata by using weights for my residuals. How can I implement an error on xdata? I hope I don't have to switch fitting routines, because I now use the lmfit package which is brilliant.
http://cars9.uchicago.edu/software/python/lmfit/

A: Sounds like orthogonal distance regression:
http://docs.scipy.org/doc/scipy/reference/odr.html


text:
Q: rbenv won't hold a global version I am trying to use rbenv to manage ruby versions, but I am having issues keeping that version when switching users.  I also concerned that my www-data user is not picking rbenv's ruby versions up, but I don't have any proof that it is doing this other than my inability to switch users.
Ruby 2.2.3 is set as the global ruby version as explained in the rbenv docs, this works for the user deploy.  In my ~/.bashrc (for user deploy), i have the following code:
export PATH="$HOME/.rbenv/bin:$PATH"
eval "$(rbenv init -)"

When I login as deploy, everything works fine.  However, when I su to root, my ruby version is broken.  Here's what it looks like when I work on the command line:
> deploy@localhost:/var/www/my_app/current$ ruby -v ruby 2.2.3p173
> (2015-08-18 revision 51636) [x86_64-linux]
> deploy@localhost:/var/www/my_app/current$ su root Password:
> root@localhost:/var/www/my_app/current# ruby -v ruby 1.9.3p484
> (2013-11-22 revision 43786) [x86_64-linux]
> root@localhost:/var/www/my_app/current# su deploy
> deploy@localhost:/var/www/my_app/current$ ruby -v ruby 2.2.3p173
> (2015-08-18 revision 51636) [x86_64-linux]

I originally installed rbenv as root, but this broke because no other user accounts could access rbenv because of permission issue!  After learning this, I installed it as deploy, and it works fine under that account, but not for any other accounts.  Any other users can't even access rbenv...
Did I do something wrong?!  Thanks for your help!

A: You're running into this issue because rbenv is designed to work on a per user basis, not as a "global" program. You've seen these symptoms:

*

*Installing for www-data gives root odd issues

*Installing as root gives www-data access issues

My preferred option would be to install rbenv individually for root and www-dev. I'd go that route since it limits the number of accounts that have access to rbenv/ruby, following best practices of limiting executables/liability on systems.
As an alternative, you can install rbenv so that all users have access to it. For that you can use /etc/profile.d:
# From: https://gist.github.com/jnx/1256593#file-rbenv-install-system-wide-sh
# Install rbenv
git clone git://github.com/sstephenson/rbenv.git /usr/local/rbenv

# Add rbenv to the path:
echo '# rbenv setup' > /etc/profile.d/rbenv.sh
echo 'export RBENV_ROOT=/usr/local/rbenv' >> /etc/profile.d/rbenv.sh
echo 'export PATH="$RBENV_ROOT/bin:$PATH"' >> /etc/profile.d/rbenv.sh
echo 'eval "$(rbenv init -)"' >> /etc/profile.d/rbenv.sh

chmod +x /etc/profile.d/rbenv.sh
source /etc/profile.d/rbenv.sh

This ought to setup rbenv for any user that uses the system -- for better or worse.


text:
Q: Why is my program not connecting to the database? I'm creating a database so I can store usernames and passwords. I have successfully created a DB on Microsft Visual Express C# 2010.
My program seems to be working fine, and produces no error message, except that I'm not getting any feedback: it looks like my program is not actually making the request to the database, or not returning the results. What's going on?
    private void button1_Click(object sender, EventArgs e)
    {
        string connection = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True";
        SqlConnection cn = new SqlConnection(connection);
        try
        {
            cn.Open();
        }
        catch (Exception)
        {
            MessageBox.Show("Did not connect");
        }
        string username = textBox1.Text;
        string password = maskedTextBox1.Text;
        string sqlquery = ("SELECT * FROM User WHERE Username = '" + textBox1.Text + "'");
        sqlquery = "INSERT INFO [User] (Username, Password) VALUES ('" + textBox1.Text + "','" + maskedTextBox1.Text + "')";
        SqlCommand Command = new SqlCommand(sqlquery, cn);
        Command.Parameters.AddWithValue("Username", username);
        Command.Parameters.AddWithValue("Password", password);
    }
    private void Form1_load(object sender, EventArgs e)
    {
        string connection = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True";
        SqlConnection cn = new SqlConnection(connection);
        try
        {
            cn.Open();
        }
        catch (Exception)
        {
            MessageBox.Show("Did not connect");
        }
    }

}

}

A: You're not actually executing the SqlCommand, so it seems logical that you would not "see" anything happen. Try adding the following line to the end of button1_Click:
Command.ExecuteNonQuery(); // actually execute the INSERT INFO... query

You have some issues with your SQL code, but you'll receive exceptions for them once you execute the command.


text:
Q: Vue.js - v-model binding a hidden input I have the following hidden input:
 <input id="myHiddenInput"
    name="myHiddenInput"
    type="hidden"
    v-model="comment.myHiddenInput"
    v-on:change="comment.myHiddenInput=$event.target.value">

var app = new Vue({
   el: '#app',
   data: {
     comment: {'myHiddenInput': ''}
   }
})

In my javascript fucntion I set the hidden value and trigger a change event as follows:
var myFunction = function () {

   $('#myHiddenInput').val(JSON.stringify(hiddentStuff)).trigger('change');

};

However the above doesn't work i.e. the two way binding does not work.
But if I do this it works:
var myFunction = function () {

   $('#myHiddenInput').val(JSON.stringify(hiddentStuff)).trigger('change');
   document.getElementById('myHiddenInput').dispatchEvent(new Event('change'));

};

Why is .trigger('change') not sufficient on its own, why do i need to calldispatchEvent(new Event('change')) aswell ?

A: You can use local browsers variables with Js when You use jquery and vue.js

A: I would advice to not use jquery in this way together with Vue.
Try to change the binded object the vue way instead:
this.comment.myHiddenInput = JSON.stringify(hiddentStuff); //Your new value here

This will automatically update the input and also trigger the change.


text:
Q: TDD Swift Unit testing a function with no inputs I'm playing with Unit testing in Swift. I can mock and test most of my functions. However I'm struggling with this one (it's for a quiz):
public func getQuestionSetStats() -> (numberOfQs: Int, answered: Int, totalCorrect: Int, totalWrong: Int)? {
    guard questionSet != nil && questionSet!.count > 0 else {return nil}
    let number = questionSet!.count
    let answered = questionSet!.filter{ $0.answerGiven != nil && $0.answerGiven ?? 0 >= 0 }.count
    let correct = Array ( zip(questionSet!.map{ Int( $0.question.solution) }, questionSet!.map{ $0.answerGiven }) )
    let correctAnswers = correct.filter{ $0.0 == ( ($0.1 ?? 10) + 1)}.count
    let wrong = number - correctAnswers
    return (numberOfQs: number, answered: answered, totalCorrect: correctAnswers, totalWrong: wrong)
}

This basically returns the state of my quiz manager for display by some view controller.
Since the vars are very much caught up in the state of the quiz manager I don't know how to unit test this function without setting up a whole state for the function - what is the best approach to do this.


text:
Q: Preventing duplicates with addError So basically was trying to prevent duplicates in my Lead Trigger by checking the lead's email and crossing it with the Contact object in order to verify that no contact with the same email exists.
The problem is that when I tried using the addError in the before insert event, I found that all the leads in the trigger got rolled back instead of just the one that was duplicated.
This is the code I used in the trigger:
public static void addErrorIfContactExists(List<Lead> newLeadList) {
        Map<String, Lead> leadsByPrimaryEmail = new Map<String, Lead>();
        for(Lead lead : newLeadList) {
            leadsByPrimaryEmail.put(lead.Email, lead);
        }

        for(Contact con : [SELECT Email FROM Contact WHERE Email IN: leadsByPrimaryEmail.keySet()]) {
            if(leadsByPrimaryEmail.containsKey(con.Email)) {
                leadsByPrimaryEmail.get(con.Email).addError('A contact with this email already exists');
            }
        }
    }

And when running the following in the test, I found both were rolled back:
Lead l1 = new Lead(Company = 'Unknown', LastName = 'Error Record', Email = 'aaa@bbb.ccc'); // There is a contact with this email in DB.
Lead l2 = new Lead(Company = 'Unknown', LastName = 'Correct Record');

insert new List<Lead> {l1, l2};

So, my question is... what is the best way to do this which I'm trying to do?

A: Your calling context has to allow partial success. This approach will fail every record:
 insert recordsWithDuplicates;

This record will allow successful records to save:
Database.insert(recordsWithDuplicates, /*allOrNone*/ false);


text:
Q: Flutter/'RenderShrinkWrappingViewport does not support' error with Table I want to put a locked ListView inside a TableCell, but I get the error. How do I fix this?
Since the error is the same, I'm substituting ListView, but the actual code uses MasonryGridView.count(), so I can't use Row, and then I want the width of the Cell to match the length of the List, so I can't specify it either.
class TableTest2 extends StatelessWidget {
  const TableTest2({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    List<String> data = ['1', '2', '3'];

    return Scaffold(
      body: Center(
        child: Table(
          columnWidths: const {0: IntrinsicColumnWidth()},
          defaultVerticalAlignment: TableCellVerticalAlignment.middle,
          children: [
            TableRow(
              children: [
                SizedBox(
                  height: 80,
                  child: ListView.builder(
                    shrinkWrap: true,
                    scrollDirection: Axis.horizontal,
                    physics: const NeverScrollableScrollPhysics(),
                    itemCount: data.length,
                    itemBuilder: (_, i) => Chip(label: Text(data[i])),
                  ),
                )
              ],
            ),
          ],
        ),
      ),
    );
  }
}

this is error message.
The following assertion was thrown during performLayout():
RenderShrinkWrappingViewport does not support returning intrinsic dimensions.
Calculating the intrinsic dimensions would require instantiating every child of the viewport, which
defeats the point of viewports being lazy.
If you are merely trying to shrink-wrap the viewport in the main axis direction, you should be able to achieve that effect by just giving the viewport loose constraints, without needing to measure its
intrinsic dimensions.

A: What the error means is that a parent widget is trying to do some logic on its children sizes ("intrinsic dimensions") but one of the children doesn't support returning those "intrinsic dimensions".
Here, I guess Table is the one that checks the intrinsic dimensions, and ListView.builder is the one that doesn't support returning intrinsic dimensions.
A way you can solve it is to use a SingleChildScrollView and a Column:
class TableTest2 extends StatelessWidget {
  const TableTest2({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    List<String> data = ['1', '2', '3'];

    return Scaffold(
      body: Center(
        child: Table(
          columnWidths: const {0: IntrinsicColumnWidth()},
          defaultVerticalAlignment: TableCellVerticalAlignment.middle,
          children: [
            TableRow(
              children: [
                SizedBox(
                  height: 80,
                  child: SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    physics: const NeverScrollableScrollPhysics(),
                    child: Column(
                      children: data.map((data) => Text(data)).toList(),
                    ),
                  ),
                )
              ],
            ),
          ],
        ),
      ),
    );
  }
}

or you can keep your ListView.builder, but you will have to remove
columnWidths: const {0: IntrinsicColumnWidth()},

What was happening?
In flutter, you are not supposed to do any logic with sizes when building the widget tree, you only have access to the constraints. This this documentation.

Constraints go down. Sizes go up. Parent sets position.

This is a design choice made to make the layout of the widget tree performant since it has to go through the widget tree only once.
However, there are still some widgets that apply some logic from the size of their children (like IntrinsicHeight) but it comes with a cost it renders the layout more than once:

This class is relatively expensive, because it adds a speculative layout pass before the final layout phase. Avoid using it where possible. In the worst case, this widget can result in a layout that is O(N²) in the depth of the tree.

When you try to use the IntrinsicColumnWidth with your Table, the Table will try to layout each child several times, look at their sizes, and then decide what is the best one.
However ListView.builder is lazy (see this documentation), so it doesn't render all its children, only the ones you can see on the screen. This is also done for performances (think about the case where you have an infinite number of children).
It means the ListView.builder cannot know its size because it cannot render all its children. Therefore, it doesn't support returning intrinsic dimensions as your error states.

A: The issue is coming from using IntrinsicColumnWidth, you can choose other classes like  FixedColumnWidth, FractionColumnWidth... or create new class with extending TableColumnWidth
child: Table(
  columnWidths: const {
    // 0: IntrinsicColumnWidth(), // remove/replace this
  },


text:
Q: Git feature branch: getting only one merge commit Following situation. I work on feature branches in git which I merge into common develop branch when I'm finished with the corresponding feature. Since it can take considerable time to get a feature completed, I merge the develop into my feature branch on a regular basis, to keep getting updates of code by my colleagues.
Now, when I'm finished and merge my feature branch into develop, all commits I've done on the feature branch appear in the history of develop. But I would like to have only one merge commit to keep the history clear. I don't need all the intermediate stuff.
Is that possible?

A: Here is what you do in such situation

*

*Checkout your feature branch

*Run git rebase develop

*Checkout your develop branch

*Run git merge feature
Done


text:
Q: Trying to initialize a list with values but not working when I use a variable to create the size This is my second time using C++ and I'm trying to port some Java code I made but am having trouble understanding some behavior. I have a list of data and want to create another list of the same size but the values are default to zero(in Java I use Arrays.fill(list, 0); after creating it). When I try to do something similar in C++ I get variable-sized object 'list1' may not be initialized
Here's a code to better example:
#include <iostream>
#include <boost/assign/std/vector.hpp> // for 'operator+=()'

using namespace std;
using namespace boost::assign;

int main()
{
    cout << "Hello World!" << endl;
    vector<short> data;
    data += -40, -30,-10, 20, 50;

    //int coeff [data.size()];
    cout << "data array size is " << data.size() << endl;
    short list1 [data.size()] = {0}; //does not work
    for (int i =0; i<data.size(); i++) {
        cout << "data is " << list1[i] << endl;
    }

    cout << "********** try 2 **************" << endl;
    //this works if I use a actual number to create the list but I want to declare it at runtime
    short list2 [5] = {0};
    for (int ii=0;ii<5;ii++) {
        cout << "data is " << list2[ii] << endl;
    }

    return 0;
}

Like I mentioned, I'm completely green when I comes to C++ (I have read a book and done a few tutorials) so I may be doing something completely wrong.  In the event I cannot do this at runtime and only at compile time, is there something else I can use to get the same result?

A: c++ does not have dynamically sized arrays, so this is illegal:
short list1 [data.size()];

but you can use a vector:
std::vector<short> list1(data.size(),0);

That creates a vector of the same length as data, full of zeroes.

A: If you want an array whose size is determined at runtime, you'll have to allocate it.
short * list1 = new short[data.size()];
//do stuff
delete [] list1; //we don't want to leak

You typically want to avoid naked pointers whenever possible, so the cleaner solution is what juanchopanza suggested and try to use std::vector.

A: The equivalent of Arrays.fill(list, 0); for a C++ vector looks like std::fill(list.begin(), list.end(), 0);
You can also simply declare a std::vector<short> list1(data.size()); to create it with zero initialized values or with a specific value std::vector<short> list1(data.size(), 0);


text:
Q: By-function in R I'm trying to get familiar with the by-function in r. For some reasen I cannot get it to work properly. I try to count mean for every value for every sample plot.
I have following data:
       PuuID Sampleplot Value1 Value2 Value3
1      1          a      1      2      2
2      2          a      2      1      3
3      3          b      4      6      2
4      4          b      5      5      5
5      5          b      4      6      4
6      6          c      5      5      8
7      7          c      3      2      9
8      8          c      5      2      7
9      9          c      6      5      8
10    10          c      5      4      8
11    11          c      6      6      2

So far I have tried following:
data<-read.csv2("c:/data/data.csv", header = TRUE)
attach(data)
by(data[, 3:5], Sampleplot, mean)

and get following error:
Sampleplot: a
[1] NA
-------------------------------------------------------------------------------------
Sampleplot: b
[1] NA
-------------------------------------------------------------------------------------
Sampleplot: c
[1] NA
Warning messages:
1: In mean.default(data[x, , drop = FALSE], ...) :
  argument is not numeric or logical: returning NA
2: In mean.default(data[x, , drop = FALSE], ...) :
  argument is not numeric or logical: returning NA
3: In mean.default(data[x, , drop = FALSE], ...) :
  argument is not numeric or logical: returning NA

What am I doing wrong?

A: Your numbers are being read in as factors. Use stringsAsFactors=F in your read.csv2. And use as.numeric(data[,3:5]). If you have NA in your data use by(data[, 3:5], Sampleplot, mean,na.rm=T).
Alternatively, turn the columns into numeric columns first. data[,3:5]=sapply(data[,3:5],function(x) { as.numeric(as.character(x)) } )
Note: I changed the conversion of column type from as.numeric to function(x) { as.numeric(as.character(x)) } because not all of your factors seem to start from 1.

A: As a style issue it is better never to use attach but the real problem is that colMeans is needed here rather than mean:
> Sampleplot <- data$Sampleplot
> by(data[3:5], Sampleplot, colMeans)
Sampleplot: a
Value1 Value2 Value3
   1.5    1.5    2.5
------------------------------------------------------------
Sampleplot: b
  Value1   Value2   Value3
4.333333 5.666667 3.666667
------------------------------------------------------------
Sampleplot: c
Value1 Value2 Value3
     5      4      7

or with rbind:
> do.call("rbind", by(data[3:5], Sampleplot, colMeans))
    Value1   Value2   Value3
a 1.500000 1.500000 2.500000
b 4.333333 5.666667 3.666667
c 5.000000 4.000000 7.000000

If you want to use mean then use aggregate like this:
> aggregate(data[3:5], data[2], mean)
  Sampleplot   Value1   Value2   Value3
1          a 1.500000 1.500000 2.500000
2          b 4.333333 5.666667 3.666667
3          c 5.000000 4.000000 7.000000

or aggregate.formula:
> aggregate(. ~ Sampleplot, data[2:5], mean)
  Sampleplot   Value1   Value2   Value3
1          a 1.500000 1.500000 2.500000
2          b 4.333333 5.666667 3.666667
3          c 5.000000 4.000000 7.000000

By the way, this is what was used for data (next time please use dput to output it in this form for reproducibility sake):
data <- structure(list(PuuID = 1:11, Sampleplot = structure(c(1L, 1L,
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("a", "b", "c"
), class = "factor"), Value1 = c(1L, 2L, 4L, 5L, 4L, 5L, 3L,
5L, 6L, 5L, 6L), Value2 = c(2L, 1L, 6L, 5L, 6L, 5L, 2L, 2L, 5L,
4L, 6L), Value3 = c(2L, 3L, 2L, 5L, 4L, 8L, 9L, 7L, 8L, 8L, 2L
)), .Names = c("PuuID", "Sampleplot", "Value1", "Value2", "Value3"
), class = "data.frame", row.names = c("1", "2", "3", "4", "5",
"6", "7", "8", "9", "10", "11"))


text:
Q: How can I use `TRIM` while sorting on a Group_Concat column? I have a MySQL query that looks similar to the following
SELECT
    ta.*,
    GROUP_CONCAT(tb.value) AS `grouped_value`
FROM
     test.test_a ta
INNER JOIN test.test_b tb ON tb.id = ta.t_id
GROUP BY ta.t_id
ORDER BY `grouped_value` ASC

I am using the GROUP_CONCAT function to create a comma-separated value, aliased as grouped_value. The query above works as it should, but grouped_value may contain leading space and messes with sorting of the final results. I attempted to use the TRIM function, but that does not appear to work in this instance.
SELECT
        ta.*,
        GROUP_CONCAT(tb.value) AS `grouped_value`
FROM
    test.test_a ta
INNER JOIN test.test_b tb ON tb.id = ta.t_id
GROUP BY ta.t_id
ORDER BY TRIM(`grouped_value`) ASC

Error Message

Error Code: 1247 - Reference 'grouped_value' not supported (reference to group function)

Is it possible to use TRIM while sorting on a group concatenated column? If not, what is a work around for this error?

A: It looks like you want to trim each of the individual values in your list. In that case place it inside the GROUP_CONCAT call:
SELECT
    ta.*,
    GROUP_CONCAT(TRIM(tb.value)) AS grouped_value
FROM
     test.test_a ta
INNER JOIN test.test_b tb ON tb.id = ta.t_id
GROUP BY ta.t_id
ORDER BY grouped_value ASC

As discussed in comments, if you need to keep the white-space in the displayed values, then you would just do the trimming in the order by clause:
ORDER BY GROUP_CONCAT(TRIM(tb.value)) ASC

A: You are uing a aggegatioin function without group by  ( and you should esplicitally set the column name in select and group by )
eg:  assuming you have col1 and col2 from ta yous should
SELECT
    ta.col1, ta.col2,
    GROUP_CONCAT(tb.value) AS `grouped_value`
FROM
     test.test_a ta
INNER JOIN test.test_b tb ON tb.id = ta.t_id
GROUP BY ta.col1, ta.col2,
ORDER BY `grouped_value` ASC

anf for trim  simple apply to result
SELECT
    ta.col1, ta.col2,
    trim(GROUP_CONCAT(tb.value)) AS `grouped_value`
FROM
     test.test_a ta
INNER JOIN test.test_b tb ON tb.id = ta.t_id
GROUP BY ta.col1, ta.col2,
ORDER BY `grouped_value` ASC


text:
Q: PHP - identify user by url id I've 3 buttons to rank my users. Admin, Member and a button to ban them. So now I wanted to identify them by their "url-id" with $_GET. But when I do that I get an error:

Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE),
  expecting identifier (T_STRING) or variable (T_VARIABLE) or number
  (T_NUM_STRING).

How can I fix that? I appreciate every help!
<?php
 include_once('connection.php');
 if (isset($_POST['ban'])) {
  $sql = "UPDATE
          t_user_info
        SET
          user_level = 3
        WHERE
          id = $_GET['id']";

$query = $conn->prepare($sql);
$query ->execute(array('user_level' => $user_level));

session_unset();
session_destroy();
header('Location: /PHP/index.php?page=ban');
}
if (isset($_POST['admin_btn'])) {
 $sql = "UPDATE
          t_user_info
        SET
          user_level  = 1
        WHERE
          id       = $_GET['id']";

$query = $conn->prepare($sql);
$query ->execute();
header('Location: /PHP/index.php?page=admin');

}

if (isset($_POST['member_btn'])) {
$sql = "UPDATE
          t_user_info
        SET
          user_level  = 2
        WHERE
          id       = $_GET['id']";

$query = $conn->prepare($sql);
$query ->execute();
header('Location: /PHP/index.php?page=member');

}

?>

A: Your update query had a syntax error and you were not binding the right values. Try this:
<?php
include_once('connection.php');
if (isset($_POST['ban'])) {
    $sql = "UPDATE
            t_user_info
            SET user_level = 3
            WHERE id = :id";

    $query = $conn->prepare($sql);
    $query ->execute(array(':id'=>$_GET['id']));

    session_unset();
    session_destroy();
    header('Location: /PHP/index.php?page=ban');
    exit;
}

if (isset($_POST['admin_btn'])) {
    $sql = "UPDATE
            t_user_info
            SET user_level  = 1
            WHERE id = :id";

    $query = $conn->prepare($sql);
    $query ->execute(array(':id'=>$_GET['id']));
    header('Location: /PHP/index.php?page=admin');
    exit;
}

if (isset($_POST['member_btn'])) {
    $sql = "UPDATE t_user_info
            SET user_level  = 2
            WHERE id = :id";

    $query = $conn->prepare($sql);
    $query ->execute(array(':id'=>$_GET['id']));
    header('Location: /PHP/index.php?page=member');
    exit;
}

?>


text:
Q: prettyPhoto: how to dynamically add photos to open gallery I have an image-gallery using prettyPhoto. I use the api for loading the photos in it.
The first photo is available in a data-attribute on the thumbnail. The rest of the images are being fetched with an AJAX-call.
The first photo of the album (the one that is already in the DOM) is being shown perfectly. But in the success-function of the AJAX call I'm reloading the gallery with the new images. That part isn't working.
What am I doing wrong?
HTML: (I removed unnecassary elements)

JAVASCRIPT:
$('#gallery').on('click','.albumTrigger',function(e) {
  // initialize gallery
  $.fn.prettyPhoto({
    slideShow: 3000,
    theme: 'dark_rounded',
    social_tools: ''
  });

  var api_images = [];
  var api_titles = [];
  var api_descriptions = [];
  var albumData = $(this).find('.thumbImage').data('album');
  $.each(albumData,function(index,item) {
    api_images.push(item.url);
    api_titles.push(item.name);
    api_descriptions.push(item.wf_description);
  });
  $.prettyPhoto.open(api_images,api_titles,api_descriptions);

  // Get rest of images via ajax
  $.get('/gallery',{
    'id': $(this).attr('rel'),
    'method': 'getAlbumImages'
  },function(albumData) {
    // I did console.log(albumData); here, and there was data
    // add images to gallery
    $.each(albumData,function(index,item) {
      api_images.push(item.url);
      api_titles.push(item.name);
      api_descriptions.push(item.description);
    });
    $.prettyPhoto.open(api_images,api_titles,api_descriptions);

  });

  e.preventDefault();

});

EDIT:
If I remove the first block of code what opens prettyPhoto it works perfect. But now the gallery opens after the ajax-call has run.
The idea kinda is that while the ajax-call is running, the user already sees the album-photo.

A: Try changing your second .open call to first close the gallery then open it again:
$.prettyPhoto.close();
$.prettyPhoto.open(...);


text:
Q: Is there a possibility to set a notification to warn developers about any Db structure change done? Is there any tool or a way to let all the developers to be notified if a Db guy or someone within the team makes a change in Db like adding a new column to a table or renaming etc. ?
Maybe a notification email to be sent on any modifications on table structures...
Any advice?
Thanks!

A: It deppends on the DB engine, but you got the triggers, and you can "trigger" them under certain events, for example a change in the DB structure. Every DB engine works with its own triggering system, that's because I don't give you any example. Just examine the doc of yours, or tell us which is yours, and we'll help you also with that.

A: You can construct a simple schema version table, which is updated each time the database schema is changed by someone. The schema version (i.e the one which the developers are assuming) is held in a config file somewhere, and if a conflict arises, this should be made obvious.
e.g. schema version table in the database has ID = 20110603 and your config file has something like:
db.schema.version=20110529

then, when your app starts, compare the two IDs and log/throw a message as appropriate. That way, you know if you are working against the latest db structure.


text:
Q: Erro de repente no sistema de login Eu estava fazendo um sistema de login e estava funcionando tudo perfeitamente de repente eis que aparece este erro abaixo:

Fatal error: Uncaught Error: Cannot use object of type stdClass as
  array in
  C:\xampp\htdocs\PC\gentelella-master\production\Controllers\valida.php:24
  Stack trace: #0 {main} thrown in
  C:\xampp\htdocs\PC\gentelella-master\production\Controllers\valida.php
  on line 24

valida.php
<?php
    session_start();
    //Incluindo a conexão com banco de dados
    require_once("config.php");

    $conn = new Conexao();
    //O campo usuário e senha preenchido entra no if para validar
    if((isset($_POST['user'])) && (isset($_POST['senha']))){
        $usuario = $_POST['user'];
        $senha = $_POST['senha'];

        //Buscar na tabela usuario o usuário que corresponde com os dados digitado no formulário
        $resultado = $conn->select("SELECT * FROM usuarios WHERE BINARY nome = '$usuario' and BINARY senha = '$senha' LIMIT 1");

        if (count($resultado) <= 0) {
            $_SESSION['loginErro'] = "Usuário e/ou senha Inválidos";
            header("Location: ../Views/logincs.php");
        }

        $res = $resultado[0];
        //Encontrado um usuario na tabela usuário com os mesmos dados digitado no formulário
        if(isset($resultado)) {
            $_SESSION['usuarioId'] = $res['id'];
            $_SESSION['usuarioNome'] = $res['nome'];
            $_SESSION['usuarioNiveisAcessoId'] = $res['nivel'];
            $_SESSION['senha'] = $res['senha'];
            $_SESSION['OK'] = true;
            if($_SESSION['usuarioNiveisAcessoId'] == 1 or $_SESSION['usuarioNiveisAcessoId'] == 2){
                header("Location: ../Views/index.php");
            } else if ($_SESSION['usuarioNiveisAcessoId'] == 3 or $_SESSION['usuarioNiveisAcessoId'] == 4){
                header("Location: ../Views/index.php");
            }
            //Não foi encontrado um usuario na tabela usuário com os mesmos dados digitado no formulário
            //redireciona o usuario para a página de login
        }
        //O campo usuário e senha não preenchido entra no else e redireciona o usuário para a página de login
    }
?>

A: Verifique com var_dump se $res é um array ou um objeto. Se for um objeto, altere as declarações como $res['nome']; para $res->nome;


text:
Q: MySQL : graph tool to show variables i need to graph ( with gnuplot or other tools), some variables on a machine running MySql engine . I'm interested on a slow queries vs time, and CPU usage
Have any suggestions?

A: I'm not sure, but mysql monitor is what You can look at

A: You should try MONyog-MySQL MOnitor and Advisor from webyog. It has all things what you have mentioned. A typical Real-Time view looks like this.


text:
Q: How to insert multiple records in tableA based on tableB records row? I have Table A and Table B as below:-
Table A
user_id|sub_category_id|category_id|is_removed
5      |201            |2          |false

Table B
sub_category_id|category_id
101            |1
102            |1
103            |1
201            |2

May I know how to insert multiple records into Table A base on Table B if Category_id is 1 with user_id is 5 and is_removed is false?
Thank you.

A: Short answer:
given the two tables described:
insert into A (select 5, sub_category_id, category_id, false from B where category_id = 1);

Detailed explanation:
A content:
select * from A;
+---------+-----------------+-------------+------------+
| user_id | sub_category_id | category_id | is_removed |
+---------+-----------------+-------------+------------+
|       5 |             201 |           2 |          0 |
+---------+-----------------+-------------+------------+

B content:
select * from B;
+-----------------+-------------+
| sub_category_id | category_id |
+-----------------+-------------+
|             101 |           1 |
|             102 |           1 |
|             103 |           1 |
|             201 |           2 |
+-----------------+-------------+

Create a view:
select 5, sub_category_id, category_id, false from B where category_id = 1;
+---+-----------------+-------------+-------+
| 5 | sub_category_id | category_id | FALSE |
+---+-----------------+-------------+-------+
| 5 |             101 |           1 |     0 |
| 5 |             102 |           1 |     0 |
| 5 |             103 |           1 |     0 |
+---+-----------------+-------------+-------+

Insertion:
insert into A (select 5, sub_category_id, category_id, false from B where category_id = 1);
+---------+-----------------+-------------+------------+
| user_id | sub_category_id | category_id | is_removed |
+---------+-----------------+-------------+------------+
|       5 |             201 |           2 |          0 |
|       5 |             101 |           1 |          0 |
|       5 |             102 |           1 |          0 |
|       5 |             103 |           1 |          0 |
+---------+-----------------+-------------+------------+


text:
Q: Counting matchings in middle levels of the Boolean lattice Let $k$ be a nonnegative integer and consider $C_k$, the set of all subsets $A$ of size $k$ in $[2k+1]=\{1,2,\ldots,2k+1\}$ as well as $C_{k+1}$, the set of all subsets $B$ of size $k+1$ in $[2k+1]$. Consider the bipartite graph $G_k$ with vertex set $C_{k}\cup C_{k+1}$ and edges corresponding to inclusions $A\subset B$. Finally, let $M_k$ be the number of perfect matchings in the graph $G_k$.
Question: Where can I find evaluations of $M_k$, if not in general, at least for some values of $k$?
I know that such matchings were considered, e.g., by Kierstead and Trotter, in relation to the middle levels conjecture (now a theorem), but I did not see tables of values of $M_k$.


text:
Q: Flutter Intl library value.format to get . or , in thousands I'm using the Intl library because I want to have thousands divided by the relative symbol (., as for example).
Then I want to have this: 12230
Modified to this: 12.230 (in my locale)
I would like to use Intl library because it has the locale automatism.
My code is:
final TextEditingController kcalEditingController =
              TextEditingController();
          kcalEditingController.addListener(() => setState(() {
                if (kcalEditingController.text.length > 3) {
                  NumberFormat numberFormat =
                      NumberFormat.decimalPattern(Platform.localeName);
                  kcalEditingController.text = numberFormat.format(int.parse(
                      kcalEditingController.text
                          .replaceAll(RegExp('[.,]'), '')));
                }
              }));

Anyway when I try to insert: 1254 all it's ok: result 1.254
By typing now eg. the number 5, the new result is: 51.254 (and not 12.545)
Also, after 4 digits, the 0 (zero) number stop responding...
As I can see, after typed the fourth number, the called the .format function, the cursor move to start (in my example before the number 1) and I'm non able, even manually or with mouse, to move it in last position (even in my example after the number 4).

A: You should use a TextInputFormatter as in the following snippet:
TextFormField(
  controller: kcalEditingController ,
  decoration: InputDecoration(
    labelText: "My numeric field",
  ),
  inputFormatters: [NumberFormatter() ],
  keyboardType: TextInputType.numberWithOptions(decimal: true, signed: true),
),

import 'package:flutter/services.dart';
import 'package:intl/intl.dart';

class NumberFormatter extends TextInputFormatter {
  final NumberFormat numberFormat = NumberFormat.decimalPattern(Intl.getCurrentLocale());

  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    final text = newValue.text.length > 3 ? numberFormat.format(int.parse( newValue.text.replaceAll(RegExp('[.,]'), ''))) : newValue.text;
    return TextEditingValue(
      text: text,
      selection:  TextSelection.collapsed(offset: text.length)
    );
  }
}


text:
Q: Best way to extract values from a list of rules? Mathematica has a lot of list manipulation functions, and, also because I don't work with lists often, at times I'm a bit lost. I'll find a way, but I'm sure it's not the most efficient. Case in point, this list:
list = {{x -> -1, y -> 5}, {x -> -1, y -> 6}, {x -> -1, y -> 7}, {x -> 0, y -> 2},
 {x -> 0, y -> 3}, {x -> 0, y -> 4}, {x -> 0, y -> 5}, {x -> 0, y -> 6},
 {x -> 0, y -> 7}, {x -> 1, y -> 2}, {x -> 1, y -> 3}, {x -> 1, y -> 4},
 {x -> 1, y -> 5}, {x -> 1, y -> 6}, {x -> 1, y -> 7}, {x -> 2, y -> 3},
 {x -> 2, y -> 4}, {x -> 2, y -> 5}, {x -> 2, y -> 6}, {x -> 2, y -> 7},
 {x -> 3, y -> 4}, {x -> 3, y -> 5}, {x -> 3, y -> 6}, {x -> 3, y -> 7},
 {x -> 4, y -> 5}, {x -> 4, y -> 6}, {x -> 4, y -> 7}, {x -> 5, y -> 6},
 {x -> 5, y -> 7}, {x -> 5, y -> 8}, {x -> 6, y -> 7}, {x -> 6, y -> 8}, {x -> 7, y -> 8}}

I just need the numerical data, then this function:
Transpose[{list[[All, 1]][[All, 2]], list[[All, 2]][[All, 2]]}]

gives me the desired result, but it doesn't look good, and I'm afraid of wearing out my [ and ] keys.
{{-1, 5}, {-1, 6}, {-1, 7}, {0, 2}, {0, 3}, {0, 4}, {0, 5}, {0, 6}, {0, 7},
 {1, 2}, {1, 3}, {1, 4}, {1, 5}, {1, 6}, {1, 7}, {2, 3}, {2, 4}, {2, 5},
 {2, 6}, {2, 7}, {3, 4}, {3, 5}, {3, 6}, {3, 7}, {4, 5}, {4, 6}, {4, 7},
 {5, 6}, {5, 7}, {5, 8}, {6, 7}, {6, 8}, {7, 8}}

What's the best way to extract the data from the list?

A: While I would actually use list[[All, All, 2]] as I have yet to find a case where that is not fastest, you could also do this with Apply:
Apply[#2 &, list, {2}]

I take the comment about wearing out your keys as humorous, nevertheless read this:
Automating Esc [[ Esc formatting?

A: The easiest way is probably something like this
{x, y} /. list

A: This undocumented form of Extract can be used and it is just as fast or slightly faster that Part on my machine:
Last @ Extract[list, {{0}, {All, All, 2}}]

A: I will do
list /. Rule[a_,b_] :> b

Though less elegant, for large lists replacement using patterns seems faster.
list = Table[{x -> RandomReal[], y -> RandomReal[]}, {i, 100000}];
list /. Rule[a_, b_] :> b; // AbsoluteTiming

{0.1530087, Null}

Heike's method
{x, y} /. list; // AbsoluteTiming

{0.3340191, Null}

The very efficient one from kguler
list[[All, All, 2]]; // AbsoluteTiming

{0.0370021, Null}

If I have to choose, {x, y} /. list all the way!

A: Four brackets:)
list[[All, All, 2]]

or
list[[;; , ;; , 2]]

A: Mathematica on the Raspberry Pi or version 10 of the software has a Values function which works with Associations and a list of rules. The simplest answer to this question is:
Values@list