text:
Q: Use of comment_reply_link_args filter i am trying to create a filter like this
add_filter('comment_reply_link_args','change_author_title');
function change_author_title( $args ) {
  $defaults = array(
        'add_below'     => 'comment',
        'respond_id'    => 'respond',
        'reply_text'    => __( 'Reply' ),
        /* translators: Comment reply button text. %s: Comment author name. */
        'reply_to_text' => __( 'THIS TEXT' ),
        'login_text'    => __( 'Log in to Reply' ),
        'max_depth'     => 0,
        'depth'         => 0,
        'before'        => '',
        'after'         => '',
    );

    $args = wp_parse_args( $args, $defaults );
    return $args;
}

What i actually need is to filter the 'reply_to_text' from the $defaults array.
The reason behind this is that i created a filter with get_comment_author
add_filter('get_comment_author', 'my_comment_author', 10, 2);
function my_comment_author( $author, $comment_ID ) {
    if (! is_admin()) {
    // Get the comment ID from WP_Query
    $comment = get_comment( $comment_ID );
    $authoremail = get_comment_author_email( $comment);
    $user = get_user_by( 'email', $comment->comment_author_email );

    if (! email_exists($authoremail)) {
        if(mb_strlen($comment->comment_author, 'UTF-8')>13){
        $author = mb_substr($comment->comment_author,0,13, 'UTF-8').'.'; }
    } else {
        if( ! empty( $user->first_name ) ){
        $author = $user->first_name;  }
        else {
        return $author;  }
    } }

    return $author;
}

and i would like to pass the same output in $defaults array 'reply_to_text'.
Could someone give me a tip?
Thank you

A: You mean, something like this?
add_filter( 'comment_reply_link_args', 'change_author_title', 10, 2 );
function change_author_title( $args, $comment ) {
    $args['reply_to_text'] = 'Reply to ' . get_comment_author( $comment );
    return $args;
}

Explanation: I changed the function declaration so that it accepts the second parameter ($comment) which is the comment object (a WP_Comment instance), then I simply call the get_comment_author() which fires the get_comment_author hook. That way, your my_comment_author() function would be called and then you'd get the same author name for use with the reply_to_text arg.


text:
Q: Printing the values in the AH, AL, BH, and BL registers in assembler? I want to create a procedure that prints the values of the AH, AL, BH, and BL registers. I have this:
prntABHL:
    PUSH    BL
    PUSH    BH
    PUSH    AL
    PUSH    AH
    PUSH    fourNums  ! defined in data as "%d, %d, %d, %d\n"
    PUSH    _PRINTF
    SYS
    ADD SP, 12        ! reset stack
    RET

This causes four register errors on the PUSH instructions. I assume because PUSH expects a 16-bit value, and AH and AL are 8-bit values.
How can I specify the values in the AH, AL, BH, and BL registers as arguments to a function if they are not 16-bits long? Is there a reasonably straightforward way to fix this problem?

A: If all you want is to push the values of 8-bit registers as 16-bit values, it's easy if you have eg. cx or any other 16-bit general register (cx, dx, bp, si, di) free to use:
Edit: movzx is not available on pre-386 processors. Replaced with 8088/8086 instructions.
xor   cx, cx
mov   cl, bl
push  cx
mov   cl, bh
push  cx
mov   cl, al
push  cx
mov   cl, ah
push  cx

If you don't have 16-bit general register free to use, you have to save the save the value to be pushed somewhere else and push it to stack from there.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using graphviz to plot decision tree in python I am following the answer presented to a previous post: Is it possible to print the decision tree in scikit-learn?
from sklearn.datasets import load_iris
from sklearn import tree
from sklearn.externals.six import StringIO
import pydot

clf = tree.DecisionTreeClassifier()
iris = load_iris()

clf = clf.fit(iris.data, iris.target)
tree.export_graphviz(clf,    out_file='tree.dot')
dot_data = StringIO()
tree.export_graphviz(clf, out_file=dot_data)
graph = pydot.graph_from_dot_data(dot_data.getvalue())
graph.write_pdf("iris.pdf")

Unfortunately, I cannot figure out the following error:
'list' object has no attribute 'write_pdf'

Does anyone know a way around this as the structure of the generated tree.dot file is a list?
Update
I have attempted using the web application http://webgraphviz.com/. This works, however, the decision tree conditions, together with the classes are not displayed. Is there any way to include these in the tree.dot file?

A: Looks like data that you collect in graph is of type list.
graph = pydot.graph_from_dot_data(dot_data.getvalue())
type(graph)
<type 'list'>

We are only interested in first element of the list.
So you can do this one of following of two ways,
1) Change line where you collect dot_data value in graph to
(graph, ) = pydot.graph_from_dot_data(dot_data.getvalue())

2) Or collect entire list in graph but just use first element to be sent to pdf
graph[0].write_pdf("iris.pdf")

Here is what I get as output of iris.pdf

Update
To get around path error,

Exception: "dot.exe" not found in path.

Install graphviz from here
Then use either following in your code.
import os
os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'

Or simply add following to your windows path in control panel.

C:\Program Files (x86)\Graphviz2.38\bin

As per  graphviz documentation, it does not get added to windows path during installation.


text:
Q: How to increase the cell size with respect to the text size in detailTextLabel in iPhone.
*

*In my App, I have a table view with cell style value2: (cell have two labels side by side).

*In textLabel, I displayed time: which was displayed in timeLable.

*in detailTextLable, I displayed comments which was entered in commentsTextView

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier] autorelease];
    cell.detailTextLabel.numberOfLines = 0;
    cell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;

}

cell.textLabel.text = timelabel.text;
 cell.detailTextLabel.text = commentTextView.text;
    }
   //int x = cell.commentTextView.frame.size.height;

}

cell.detailTextLabel.textAlignment = UITextAlignmentLeft;
cell.textLabel.textAlignment = UITextAlignmentLeft;
return cell;

}

*

*I need to expand my cell size with respect to the length of comments entered in a text view  :'commentTextView' displayed in detailTextLabel.

*But the difference in the textLable (timelable text), it does not expand along with detailTextLabel
what to do?

A: This is always tricky to get right, for the height you need to do implement something like this.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *myLabel = "Hello World";
    CGSize labelSize = [[myLabel sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:CGSizeMake(160,MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
    return labelSize.height;
}

A: You can do it by using     - (CGFloat)tableView:(UITableView *)t heightForRowAtIndexPath:(NSIndexPath *)indexPath  delegae method of teble view , like : -
- (CGFloat)tableView:(UITableView *)t heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
   CGSize lblSize ;
   NSString *lblString ;

   lblString = [[[dataSourceArray objectAtIndex:indexPath.row] valueForKey:@"aKey"];

   lblSize = [self getLebalSize:CGSizeMake(180, 9999) aLebalText:lblString aFont:[UIFont systemFontOfSize:15]];

   return lblSize.height + 10 ;
}

//getting labelsize
- (CGSize) getLebalSize : (CGSize) maxSize aLebalText : (NSString *) lebalText aFont : (UIFont *) font
{
    CGSize expectedLabelSize = [lebalText sizeWithFont:font constrainedToSize:maxSize lineBreakMode:UILineBreakModeTailTruncation];
    return expectedLabelSize;
}


text:
Q: My Object has no method? I'm having difficulty understanding why this code isn't working. From what I can tell my syntax is correct but the console.log complains that my person object doesn't have a method setFirstName. Here's what I've got so far:
HTML
<input type="text" id="firstName">

JQuery
$(document).ready( function() {
    $("#firstName").on("change", getFirstName);

    var person = new Person();

    function Person() {
        this.firstName = "";
    }

    Person.prototype = {
        setFirstName: function(name) {
            this.firstName = name;
            console.log("My first name is: " + person.firstName);
        }
    }

    function getFirstName() {
        var firstName = $("#firstName").val();
        person.setFirstName(firstName);
    }
});

The console log displays this error and points to the "person.setFirstName(firstName)" line of code:
Uncaught TypeError: Object #<Person> has no method 'setFirstName'

It's puzzling to me that it recognizes the Person object exists but then doesn't see the method setFirstName. What have I done wrong? Help me master coders, you're my only hope.

A: The current code assigns the object literal to the prototype of Person.  Instead, assign the function to the setFirstName property of Person.prototype:
Person.prototype.setFirstName = function(name) {
        this.firstName = name;
        console.log("My first name is: " + this.firstName);
}

Explanation
To understand the error, we must first understand how prototypes work in Javascript.  When an instance of an object is created using a function constructor the instance's prototype is assigned the prototype of the constructor function.
function MyObject(){}
var myObj = new MyObject();
console.log(myObj.__proto__ == MyObject.prototype); //logs true

In the provided code, an instance of Person is created using the Person constructor function.  This causes person to be assigned the prototype of Person.
var person = new Person();
function Person() {
    this.firstName = "";
}
console.log(person.__proto__); //logs Person{}

Then the object literal containing the setFirstName function is assigned to the prototype of Person.
Person.prototype = {
    setFirstName: function(name) {
        this.firstName = name;
        console.log("My first name is: " + person.firstName);
    }
}

At this point the Person prototype is assigned to the object literal with the function, however the instance person was created before the object literal was assigned to Person's prototype.  The instance person's prototype does not refer to the object literal that was assigned to Person.prototype after its instantiation.
console.log(person.__proto__ == Person.prototype); //logs false

While not recommended, we could have resolved or avoided this issue by creating the person instance after the new prototype was assigned, such as:
$(document).ready( function() {
    $("#firstName").on("change", getFirstName);

    function Person() {
        this.firstName = "";
    }

    Person.prototype = {
        setFirstName: function(name) {
            this.firstName = name;
            console.log("My first name is: " + person.firstName);
        }
    }

    var person = new Person();
    function getFirstName() {
        var firstName = $("#firstName").val();
        person.setFirstName(firstName);
    }
});

It is much better to assign the method to a property of Person.prototype so that we do not create temporial coupling that dictates when an instance of Person can be created.
This article does an excellent job of explaining prototype and would be worth the read.


text:
Q: Why simple digital multiplexer uses OR gate to combine chip parts outs? Why not just wire together outputs of the internal AND gates. For instance, consider the following Mux scheme:

Here outputs of the internal AND gates are combined using out OR gate to produce output, but why not to just wire them together rather than use additional chip? it seems to be a common practice to wire together multiple pins so we get ONE (or True) when at least one of the internal chips produces ONE.


text:
Q: what is the relation of smooth compact supported funtions and real analytic function? What is the major difference between real analytic and test function (smooth compact supported functions). Can we find a real analytic function $f$ on $\mathbb R^n$ which is also smooth compact supported? If not then need a proof.

A: If by "test function" you mean a smooth function with compact support (as opposed to a Schwarz function), then the answer is no. Consider an analytic function $f \in C_c^\infty(\mathbb R^n)$ and a point $x$ outside of its support. Because $f$ is analytic, it must equal its own Taylor series developed at $x$, i.e. $0$, and since the radius of convergence is infinite, $f$ must be the zero function.
The upshot of this is that analytic functions are very rigid objects. Loosely speaking, perturbing an analytic function in a single point causes global changes to "ripple" out from the perturbation in order to preserve analyticity.

A: A test function is a smooth and compactly supported function, while a real analytic function is smooth and given by a power series uniformly converging at every point.
Perhaps I will only give a hint as an answer to your second question: A test function must be equal to zero everywhere outside some compact set. If it were also analytic, then what would the coefficients of its power series have to be?

A: Assume $f$ is a real-analytic test function which is not identically zero; this will lead to a contradiction. Let $K$ denote the support of $f$. The idea (also present in OP's attempt) is to expand $f$ into a power series centered at some boundary point $x_0$ of the support; find that the coefficients are all zero, obtain a contradiction. Key steps:

*

*A nonempty bounded set must have nonempty boundary (because the only sets with empty boundary are $\varnothing$ and $\mathbb R^n$).

*Let $x_0$ be a boundary point of $K$. Note that $x_0\in K$ and $x_0$ is also   a limit point of the complement of $K$.

*All derivatives of $f$ are identically zero on the complement of $K$

*They are also continuous on all of $\mathbb R^n$. By continuity they are equal to zero at $x_0$.

*The power series of $f$ centered at $x_0$ is $0+0(x-x_0)+\dots$

*Therefore, $f$ is equal to zero  in some neighborhood of $x_0$. But this contradicts the definition of support of $K$.

A: I am trying to prove that if some test function $f$ in $\Bbb R^n$ is real analytic then it must be equivalent to zero function. Please correct me if there is any problem.

Proof:
Let us define a test function,
$ f_\epsilon (x)=
\begin{cases}
\frac{C^{-1}}{\epsilon^n} e^{{\frac{-\epsilon^2}{{\epsilon^2}-|x|^2}}},  &\text{for |x|< $\epsilon$ } \\
0, & \text{everywhere else}  \\
\end{cases} $
$\color{red}{\text{Edited in: This was a false start}}$. You should work with a general test function, not  a particular one. That is, simply say: let $f:\mathbb R^n\to \mathbb R$ be a test function. By definition of a test function, $f$ has compact support. The goal is to show that if $f$ is real-analytic, then the support is  empty.

We know, this function has derivatives of all orders and also has a compact support.
Now, Let us suppose that it is also a real Analytic function.
If this function is a real analytic then it must has a Taylor series expansion about any point $x_0$ in its domain which will converge to $f_\epsilon (x)$ for a nbdd. of $x_0$.
Now in particular take Taylor expansion about $\pm\epsilon$
$f_\epsilon (x) \approx  0 + 0x + 0x^2 + . . .$
The Taylor series expansion does in fact converge to the function $f_\epsilon^˜ (x) = 0$.
We can see that $f_\epsilon^˜ (x)$ and $f_\epsilon (x)$ are two different functions for |x|< $\epsilon$.
But they must be equal since $f_\epsilon (x)$ is real analytic, which is only possible when $f_\epsilon (x) \equiv 0$.

*

*Is it enough to prove it. Personally I don't feel that its sufficient...

*If I need to elaborate it by writing its Taylor series then calculations of derivatives is again a problem for me. I don't know how to write derivatives of $f_\epsilon (x)$. And in above proof, the way I approximate its Taylor series at $\epsilon$ looks quite tricky... isn't it? Please give me your suggestions and feel free to edit this proof.

Thanks you so much.


text:
Q: Class x.Savechanges(): No suitable method found to override I want to check out db.SaveChanges() for error handling, and I put it into EFentities class' SaveChanges() method, but I have this error for SaveChanges():

No suitable method found to override

Here is my code:
public partial class EFentities
{
    EF db = new EF();

    public override int  SaveChanges()
    {
        try
        {
            return base.SaveChanges();
        }
        catch (DbEntityValidationException ex)
        {
            // Retrieve the error messages as a list of strings.
            var errorMessages = ex.EntityValidationErrors
                    .SelectMany(x => x.ValidationErrors)
                    .Select(x => x.ErrorMessage);

            // Join the list to a single string.
            var fullErrorMessage = string.Join("; ", errorMessages);

            // Combine the original exception message with the new one.
            var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

            // Throw a new DbEntityValidationException with the improved exception message.
            throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
        }
    }
}

A: You're getting No suitable methode found to override error because you're neither defining SaveChanges() virtual method in the other side of partial class, nor defining any base class where the virtual method inherits from.
The SaveChanges() method available inside System.Data.Entity.DbContext class with virtual signature like this:
public virtual int SaveChanges()

Hence, you should add DbContext as base class inherited by EFEntities to make override keyword work:
using System.Data.Entity;

public partial class EFEntities : DbContext // add this base class
{
    public override int SaveChanges()
    {
        // manual override goes here

        return base.SaveChanges();
    }
}


text:
Q: Should I use OpenLayers + GeoNetwork + GeoServer together? At the moment I'm doing an internship and my assignment is as following:

*

*design (and build) a (prototype) web application

*with a map on which the users can show selected data.

*The server collects metadata and a direct download url from the source.

*Users can download the datasets directly from the source.

*A system like this that already exists and it should be able to use layers from this system through a WMS protocol.

Now there has already been research done, but it wasn't done internally and I'm not sure if she understands what GIS is. She refers to GIS as a GIS server. GIS is the whole package though, isn't it?
The research report came up with using OpenLayers, GeoServer and GeoNetwork together.
OpenLayers is referred to as the webviewer, GeoServer as the GIS server and GeoNetwork as a geoportal.
As I understand it though, GeoNetwork can display maps just fine. Should I disregard the research done and just use GeoServer + GeoNetwork? Or maybe some other combination? As long as it's free OpenSource (part of the assignment) the language doesn't matter.
I've tried (and am still researching) to find the best solution myself, but a little nudge to the correct tools would be awesome. Before this I hadn't even heard of GIS, though I do find it pretty interesting.

A: If you download and install http://geonetwork-opensource.org, you've got all the tools you mentioned above in a single package... Also you might want to have a look at http://geonode.org, which also bundles all of these projects, but adds an easy-to-use interface.
For sure, both of these projects fit your usecase perfectly


text:
Q: Is there an R package for Monte Carlo simulations? From a little searching, I have found this package, but a colleague tells me that it doesn't work in the latest version of R. This is the first time I'm using R and I get the feeling that trying to begin with something that might not work would be a bad place to start.
So, should I try with that package, is there an alternative, or should I just try to code the Monte Carlo simulations from scratch? (most of the Monte Carlo questions I can see look like they are done without a bespoke package)


text:
Q: Tracking down the source code line of a crash from a non-debug built module I have a widows crash-dump with a call stack showing me the module!functionname+offset of the function that caused the crash. The module is built without debug information using gcc.
The cause of the crash is an exception caused by a failed to write at a given address, i.e access violation(05), write violation(01)
On my development machine I have access to the same module built with debugging information. What I'm looking for is a way to track down the corresponding source code line that caused the crash, this by using the module!functionname+offset information as starting point.
The method name of the top frame in the call stack is a class destructor
The mangled function name is _ZN20ViewErrorDescriptionD0Ev+x79
Running objdump -d  searching for the module!functionname+offset gives:
.... call *%eax
.... mov 0xffffffbc(%ebp), %eax
.... cmpl 0x0, 0x148(%eax)

trying to find this in the debug built file gives no match
The source code of the destructor only contains two delete pointerX calls.
Using gdb to load the debug built module(sharedlibrary) and then calling info line  gives me a starting and ending address, using grep on the objdump output shows the corresponding disassembled code, which looks quite much like the one from the module without debug info, but still far from the same.
!NB - The output from info line says _ZN20ViewErrorDescriptionD2Ev not _ZN20ViewErrorDescriptionD0Ev as the crash dump says.
Taken from the ABI documentation:
           ::= D1   # complete object destructor
           ::= D2   # base object destructor
Where do I go from here?
Best regards
Kristofer H

A: Unfortunately even debug/non-debug builds may have different address layouts. The only way I'm aware of to accomplish something like this is to build with debug symbols and save off a copy of that binary. Then you can deploy a stripped version without the debug information.
Your approach attempting to locate the assembly code seems the most hopeful here. I would expand that even though: Try to look at a much larger chunk of assembly in the crashed file and see if you can generate more context yourself rather than having the computer attempt to match low-level instructions that might in fact slightly differ.

A: This works on the assumption that gcc compilation is 100% deterministic. I'm not sure how valid that assumption is. However, taking the further assumption that you still have exactly the same source code you could try enabling the gcc's -S command line option and rebuilding. This will result in a set of .s files, one for each source file, containing the  assembly code. You can then search through this for the code machine code that you want to find.


text:
Q: spacing vertices evenly in igraph in r I have the following graph graph
set.seed(1410)
df<-data.frame(
"site.x"=c(rep("a",3),rep("b",3),rep("c",3),rep("d",3)),
"site.y"=c(rep(c("e","f","g"),4)),
"bond.strength"=sample(1:100,12, replace=TRUE))

library(igraph)
df<-graph.data.frame(df)
V(df)$names <- c("a","b","c","d","e","f","g")
layOUT<-data.frame(x=c(rep(1,4),rep(2,3)),y=c(4:1,3:1))
E(df)[ bond.strength < 101 ]$color <- "red"
E(df)[ bond.strength < 67 ]$color <- "yellow"
E(df)[ bond.strength < 34 ]$color <- "green"
V(df)$color <- "white"
l<-as.matrix(layOUT)
plot(df,layout=l,vertex.size=10,vertex.label=V(df)$names,
edge.arrow.size=0.01,vertex.label.color = "black")

I would like to space the vertices "g-e" evenly along the vertical distance between vertex a and d to make my current graph (see below) prettier. As you can see it is pretty crowded.

Also I would like to move the two column of vertices closer together on the x-axis but I have noticed that adjusting the x coordinates in the layout is not responding. For example the two following layouts produce graph that look exactly the same despite the drastic adjustment in the x-coordinates.
layOUT<-data.frame(x=c(rep(1,4),rep(2,3)),y=c(4:1,3:1))

layOUT<-data.frame(x=c(rep(1,4),rep(100,3)),y=c(4:1,3:1))

Thanks for any advice you may have.

A: Your second question is easier to answer: igraph rescales the layout into the rectangle spanned by (-1, -1) and (1,1) in the coordinate system. If you want to avoid this, pass rescale=FALSE to the plot function -- but in this case, it is up to you to ensure that the coordinates actually make sense and are not outside the plot area.
Regarding your first question: since you are constructing the layout manually in the layOUT variable, nothing prevents you from adjusting the Y coordinates manually. First, get the minimum and maximum Y coordinates for the vertices with X=1 from layOUT:
min.y <- min(layOUT$y[layOUT$x == 1])
max.y <- max(layOUT$y[layOUT$x == 1])

Then just space the Y coordinates of the vertices with an X coordinate of 2 evenly between min.y and max.y:
vs.on.right <- which(layOUT$x == 2)
n <- length(vs.on.right)
layOUT$y[vs.on.right] <- (0:n)*(max.y-min.y)/n + min.y


text:
Q: Make a request scoped bean singleton when request-scope is not available I have the following code to define a bean request scoped bean inside my Spring application.
@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public MyBean myBean() {
    return new MyBean(); // actually it is a more complex initialization
}

But sometimes I will want to use the same bean in a offline application where request scope is not available, only singleton and prototype are.
Is there a way to make this same bean assume a singleton form when request is not available?

A: can you rely on a spring profile ?
You could maybe extract the bean creation in a private method used by 2 @Bean with different @Scope and @Profile
Something like this :
@Bean
@Profile('prod')
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public MyBean myBeanProd() {
    return getMyBean()
}

@Bean
@Profile('test')
@Scope(value = "singleton", proxyMode = ScopedProxyMode.TARGET_CLASS)
public MyBean myBeanWithoutRequestScope() {
    return getMyBean()
}

privateMyBean getMyBean() {
    return new MyBean(); // actually it is a more complex initialization
}


text:
Q: Problema de linkagem em projeto com mais de um arquivo fonte Esta é à minha função. Dá me erro quando chamo na função main.
Este é o cabeçalho da minha função, no arquivo função1.h
int eleminar_numeros_repetidos(int *vec, int n, int *vec1);

Arquivo função1.c:
void organizar_vetor(int *vec, int n){

   int i,j;

   for(i=0 ; i <n-1; i=i+1)
   {
       for(j=i+1 ; j<n ; j=j+1)
       {
           if (*(vec +i) >*(vec+j))
           {
            int aux =*(vec+i);
            *(vec+i)=*(vec+j);
            *(vec+j)=aux;
           }

       }

   }
}

int eleminar_numeros_repetidos(int *vec, int n, int *vec1){

 organizar_vetor(vec,n);

 int i,j;

   for(i=0 ; i <n-1; i++)
   {
       for(j=i+1 ; j<n ; j++)
       {
           vec[i]=vec1[i];

            if (vec1[i] == vec1[j])
           {

            int k;
              for (k = j; k <n-1 ; k++)
              {
                  vec1[k]=vec1[k+1];
                  j--;n--;
              }

           }

       }

   }
   return n;

}

Erro:
gcc ex09.c
/tmp/ccYQaeVL.o: In function `main':
ex09.c:(.text+0x112): undefined reference to `eleminar_numeros_repetidos'
collect2: error: ld returned 1 exit status
make: *** [ex09.o] Error 1

A: Seu comando de compilação está errado:
gcc ex09.c      ### BAD!!!

Deve ser assim:
gcc -o ex09 ex09.c funcao1.c   ### GOOD :)

A: Observe a linha de comando que foi utilizada para compilar:
gcc ex09.c

Você está instruindo o compilador para gerar um executável a partir de um arquivo fonte apenas, mas seu projeto é composto por mais de um. Por isso o compilador reclama que, no momento de gerar o executável, ele não acha a implementação de uma função.
Você tem duas opções
Compilar e linkar todos os fontes ao mesmo tempo:
gcc ex09.c funcao1.c

Ou compilar os fontes individualmente e linkar em separado:
gcc -c ex09.c
gcc -c funcao1.c
gcc ex09.o funcao1.o

Lembando que o parâmetro -c instrui o gcc a apenas compilar os arquivos fonte, sem linkar o executável final.


text:
Q: C# Survey Quiz Logic I am trying to make a multiple choice quiz and need the value of the input fields that I have below:
<input class="QuizButton" type="radio" name="Q1" value="1" onclick="ShowHide('Question3', 'Question4'), Q3log(1);" > [Question Text....]

How can I make this fully clickable instead of just a radio button? I have tried using  tags instead but this did not allow me to do a
Request.Form["Q1"]

request when trying to run my results function.

A: I'm not sure what you mean by "fully clickable". If what you means is "How do I make the form element respond when either the radio button or it's text are clicked" you can use a  to do this.
<input type="radio" id="option1" />
Option 1
<input type="radio" id="option2" />
Option 2
<input type="radio" id="option2" />
Option 2

Note the for attribute. It contains the id of the input that you want to associate it with. Specifying for causes both elements to behave as a single element for the purposes of UI interaction.

A: Wrap your input into label tags, that way the whole text + radio button will be clickable.

            <input class="QuizButton" type="radio" name="Q1" value="1" onclick="ShowHide('Question3', 'Question4'), Q3log(1);">
             [Question Text....]


text:
Q: How do I get a query to return an array in MYSQL? The query code
 SELECT * FROM products
              LEFT JOIN (SELECT * FROM product_images ) as images ON products.id = images.productId
              LEFT JOIN (SELECT * FROM product_shippings ) as shipping ON products.id = shipping.productId
              WHERE products.id = :productID

I have multiple images in product_images, but it's only returning one instance.
What I want to do is get it all in a associate array, like images containing a list of images, shipping containing a list of shipping items, etc.
I know how to achieve this using separate queries, but that is way too slow according to my benchmarks.
So I want something like
 {
images:[...],
shipping[...],
productId:2,
productTitle:'Hello'
}

How do I fix this issue?

A: SELECT *
    FROM products
    LEFT JOIN product_images as images      ON products.id = images.productId
    LEFT JOIN product_shippings as shipping ON products.id = shipping.productId
    WHERE products.id = :productID

Or, to get commalists (not "arrays")
SELECT  p.id, p.title,
        GROUP_CONCAT(i.image) AS images,
        GROUP_CONCAT(s.shipping) AS shippings
    FROM products AS p
    LEFT JOIN product_images AS i     ON p.id = i.productId
    LEFT JOIN product_shippings AS s  ON p.id = s.productId
    WHERE p.id = :productID

A: If you take away the GROUP BY you will get all the images for the product.id in the WHERE clause.


text:
Q: The user gets "Unknown file type" when open docx with Word 2003 One of my customers has problems with opening of word documents. He gets "Unknown file type" when he downloads a .docx file. He has Word 2003 with plugin for .docx compatibility installed. He uses IE7 if it does matter.
The document is been sent by
return File(stream, "application/docx", fileName);

How can I solve this problem?

A: try application/msword
See here


text:
Q: Generate test cases (use case scenarios) from use case Is there any tool which can automatically extract all possible scenarios from an use case UML diagram?

A: No I don't think so.  The problem is that the Use Case diagram is almost entirely content free in UML.  It's really just a guide to how to read the use case body specifications and documents their relationships.  A test case generator would need to read the use case bodies, however UML doesn't define a standard form or semantics for them, so there's nothing for a test case generator to work with.


text:
Q: ASP.NET hidden field vs. invisible textbox what are benefits of using a hidden field in ASP.NET when we can use another invisible element such as label or text box?

A: Either way works, for text box, don't use .visible="false"
use
yourTextBox.Style.Add("display", "none")

or
yourTextBox.Style.Add("visibility", "hidden")

A: A hidden field renders as input type="hidden" in the resulting HTML. Being an input the value in the input is submitted to the server on postback while this is not the case with a label. Depending on whether or not you want that value submitted to the server you should use input or label. If you don't want the value to be submitted then label is the right solution and hidden field is wrong.
I am not sure what you mean by invisible textbox but if you are trying to make it invisible via CSS keep in mind that the input type has semantic meaning to search engines, bots, etc. Also at some point your HTML might be served without CSS or with different CSS and the text box will become visible to the user. Otherwise there are no differences between hidden field and invisible text box as both of them render inputs.

A: The hidden field generate <input type="hidden" /> element on the page, which cannot be seen but the client can get the element, set the data and pass to the server:
document.getElementById('<%= SomeHiddenField.ClientID %>').value = "data_pass_to_server";

after postback you can get the value:
var clientData = SomeHiddenField.Value; // "data_pass_to_server"

If you're using invisible textbox (<asp:TextBox Visible="False" />), there's no element generated in the html file.

A: Practically you can achieve the same thing with any of them, but since you want a "hidden field", semantically speaking the hidden field in ASP.NET is your best bet for readability reasons.


text:
Q: Strange output in cmd while batch file is running I have that script in batch file:
cd C:\TESTS\front-tests
call git pull
cd C:\TEST\front-tests\AutoApp\bin\debug
start AutoApp.exe

And git pull do not work because I can not change directory. Here is the result image:

I do not know from where do the strange symbols, before cd command, come from.
Any ideas?

A: The batch file is saved as utf-8 BOM prefixed. What you see as the cd prefix is the byte order mark.
Save the file as ANSI or utf-8 without BOM to make it work.


text:
Q: ScrollController animateTo() I want the selected item in the horizontal listView to be centered, so I first calculate the position that should animate to (scroll to), and it is always calculated correctly, but when I select an item that is far from the currently selected one, the list doesn't scroll correctly to the calculated position.
Code:
double _position =  index * (_width + 2 * _horizontalPadding)
                    + (_selectedWidth+_horizontalPadding);
_scrollController.animateTo(
                  _position,
                  duration: Duration(milliseconds: 1000),
                  curve: Curves.ease);

where _width is the width of all elements but the selected one, as its width is _selectedWidth , and horizontal padding is constant .. and index is the index of the selected item

A: Try wrapping the scroll with PostFrameCallback
WidgetsBinding.instance.addPostFrameCallback((_) {
    double _position =  index * (_width + 2 * _horizontalPadding)
                    + (_selectedWidth+_horizontalPadding);
    _scrollController.animateTo(
                  _position,
                  duration: Duration(milliseconds: 1000),
                  curve: Curves.ease);
});


text:
Q: How would you explain this SQL code in regards to select 1 from dual where exists I need to explain this to someone in laymen's terms.  How would you summarize this if you were talking to a 5 year old, lets say.
I would explain it as:

"find and display data that is from this table: a column from tableA where col1 = 5000 and col2 > ? and col3 > ? and col4 <= ?

Is there a better way you can find to word this?  Thanks.
select 1
from dual
where exists
(select 1 from tableA where col1 = 5000 and col2 > ? and col3 > ? and col4 <= ? )

A: Me: This query will return one row with a projection of 1 if there is at least one row in TABLEA where COL1 equals 5000 and COL2 is bigger than some unknown value and COL3 is bigger than some unknown value and COL4 is not bigger than some unknown value. Otherwise it will return no rows. It uses DUAL, which is a special table in Oracle guaranteed to return a single row.
Five-year-old: This code seems rather shonky. Did Spud write it? Can Bob fix it?


text:
Q: Looking for a simple Mailing List / Forum implementation for/in Python/Plone I am in the process to set up a new site with Plone, and I am looking for a simple mailing list / forum implementation.
I am aware of Mailman, of course. But what I am looking for is some hybrid solution which shows discussion threads in a web UI as well as in a users mail client and sends replies subscribers.
Or course, the UI should be managed and integrated in plone.
I'd be happy, if someone could point at the right direction. I'm lost.
For example: Looking at plone org, I see some products based on mailman, which might do the job, but no real contender. Some of the products on plone.org don't even have a description. Searching for mailman shows up kupu in the list. Clicking on this product I see the description: "The most recent released version of Kupu may be found here." Err. Yes, obviously. And what does it do?!?
Is there any simple discussion forum / mailing list product available for plone?

A: I think the widely accepted answer to this in the Plone community is that Plone is probably not the right tool to build a large forum.  This is up for debate, and to be honest I'm not sure myself, but I do know that community.plone.org uses Discourse.
Ploneboard is there of course (as @GhitaB has mentioned), but it's not getting a lot of work done on it at the moment.  You could also build your own to suit your own requirements, and you might find the Dexterity based collective.ploneboard a useful starting point for that.
Also, Plone has built in comments functionality which I guess doesn't cover so many features, but could do most of what you are looking for. People do also use a Disqus integration into plone.
Regarding searching for products - you are better off searching pypi than plone.org.  And Kupu is a rich text editor like TinyMCE - definitely not what you are looking for (but perhaps compatible with mailman?).
All the best, I'd be interested to hear which direction you end up taking.

A: Ploneboard may help you.
https://pypi.python.org/pypi/Products.Ploneboard
Some features:

*

*Forum: Show all recent activity, Show all unanswered

*Category state: Make free for all, Make moderated, Make private, Require membership to post

*Conversation state: Active, Lock

A: the coactivate.org project is based on plone and has an integration for a mailing list using Listen (found here).
you might browse the project resources on github or ask the contributors to find out how they do the mailing-list integration.

A: Here are few popular options as-a-service
https://www.discourse.org/ (used by e.g. atom.io, by Github, also OSS)
http://muut.com/ (as-a-service, sends mail notification, provides user integration (commercial)
Tons of PHP-based forums. Stay away from those as their security track records are abysmal.


text:
Q: Fill in the blank: "I say this with no _____ of pride" (Answer was "modicum") To help make this all make sense, there is a word I am looking for--I can hear it in my mind and I can say it with my lips. But I can find no source.
The phrase I hear is, "I say this with no monocomb of pride." The way I understand it is, along the lines of, "I say this without an ounce of pride," or "one bit of pride."

UPDATE:
I looked up the greek word for bit at random and found it to be kommati, so I did variations of this and came up with modicum.

A: The answer you are looking for, o' dear me, is "modicum."


text:
Q: What's the different between linkedSetOf and hashSetOf? In the Kotlin collection functions, we have
setOf, mutableSetOf, sortedSetOf, linkedSetOf and hashSetOf.
The first 3 is understood their differences. But what's the last two?
How are they different from others and from themselves?

A: You know that linkedSetOf returns a LinkedHashSet whereas hashSetOf returns a HashSet. The difference between LinkedHashSet and HashSet is that LinkedHashSet maintains the order of elements with which they were either inserted into or removed from the set whereas HashSet doesn't maintain the order.
Observe the example below (Kotlin playground, if you want to see it in action)
val set: LinkedHashSet<Int> = linkedSetOf(1, 3, 2)

println(set) // [1, 3, 2]

set.remove(3)
set += listOf(5, 4)
println(set) // [1, 2, 5, 4]

val hashSet: HashSet<Int> = hashSetOf(1, 3, 2)

println(hashSet) // [1, 2, 3]

hashSet.remove(3)
hashSet += listOf(5, 4)
println(hashSet) // [1, 2, 4, 5]

If you look at how the set is printed in different instances of addition and removal of elements, you would see that in the case of LinkedHashSet, the order in which the elements were added or removed is maintained and printed in the same order when iterated over.
Note: Just to show that HashSet doesn't sort the elements, below is an example (Kotlin playground)
val linkedHashSet = linkedSetOf("aaa","bbb","ccc")

println(linkedHashSet) // [aaa, bbb, ccc]

linkedHashSet.remove("ccc")
linkedHashSet += listOf("ddd","zzz")
println(linkedHashSet) // [aaa, bbb, ddd, zzz]

val hashSet = hashSetOf("aaa","bbb","ccc")

println(hashSet) // [aaa, ccc, bbb]

hashSet.remove("ccc")
hashSet += listOf("ddd","zzz")
println(hashSet) // [aaa, bbb, zzz, ddd]

A: linkedSetOf returns a  LinkedHasSet
hasSetOf returns a HashSet
The main difference between HashSet and LinkedHasSet is that LinkedHasSet maintains insertion order (order in which elements are inserted into LinkedHashSet). On the other hand HashSet doesn't maintain any order.


text:
Q: Что значит "question.choice_set.all"? Помогите понять код Не могу понять этот кусок:

    {% for choice in question.choice_set.all %}

{{ choice.choice_text }}

    {% endfor %}

Что делает цикл, что за choice_set.all и как они связаны с choice.choice_text?
Вот модели:
import datetime
from django.db import models
from django.utils import timezone

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

def __str__(self):
    return self.question_text

def was_published_recently(self):
    return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

def __str__(self):
    return self.choice_text

A: Это называется связанные обьекты:
question.choice_set.all - означает выбрать все   Choice связанные с текущим вопросом - то есть те  Choice, которые ссылаются на данный Question через поле ForeignKey(Question,...). All в конце вернёт итерируемый queryset, который будет содержать набор соответствующих Choice.
Ну а с choice_text вообще все просто: т.к каждый элемент полученного queryset-а будет являться экземпляром Choice, то вы можете из него обращаться к любому полю модели Choice


text:
Q: Dealing with stylesheet order and css module className overrides I have a component that has its own style, e.g.
.prompt { color: red; }

It's declared as so:
import cn from 'classnames';
import styles from './styles.css';

const MyComponent = ({className}) => {
  return (
    <div className={cn(styles.prompt, className)}>
      test
    </div>
  );
}

In my specific use case, the stylesheet for the className being passed in is actually defined and added to the head BEFORE the stylesheet from the module, so the module's css always overrides the style of the className being passed in. Something like:

Notice the background: yellow from second class is being overridden by the background from the module's own class.
Other than using !important in the secondary class, how can I work around this?

A: Based on Mr. Lister's response, I re-evaluated my existing knowledge of specificity and came up with the following solution in the higher level css:
// in app.scss
.offline.prompt {
    color: red;
}

// in app.tsx
const classes = cn(Styles.offline, Styles.prompt);
return <OfflineApp className={classes}>...</OfflineApp>;

Essentially, I just tag the module markup with another sibling class to increase specificity and target the necessary properties using that. WAY better than abusing !important.


text:
Q: publish google play with password resctriction I would like to publish an app in google play, but I want to restrict the downloading under password or something like that. Is it possible? Is there any alternative?
Many thanks in advance,

A: Short Answer:
No.
Slightly Long Answer:
Applications available on Google Play cannot be downloaded only after a user authenticates. Any such feature will have to be implemented withing your application. At best, if this feature is needed for monetary reasons, publish a paid application.
Since the OP isn't descriptive beyond what you are looking for as a feature, it will be difficult to suggest an option / alternative that might suit your requirement. However, if you have a server setup that can communicate with the app, you can implement a feature which requires users, upon installation and running your app, to Sign Up for a new account and/or Login if already registered.
Again, I will circle back to the original point. Any such feature will have to implemented within the application itself. Google Play does not have such a feature.


text:
Q: Flex bar chart with Two Y axis I am trying to create a bar char in action 3 script.
But for some reason I am getting 2 y-axis and no x axis.
Can some one help spot the error.
I have said "placement " bottom.
The chart creation method is "getBarChartData",
this method when invoked creates a barchart and adds it to a canvas.
This section is visible completely and can be called on a button click.
For some reason, the CDATA section is interfering with the preview of the snippet.
The standalone code snippet is below.

[Bindable]
 public var QUANTITY:ArrayCollection = new ArrayCollection([
   {date:"22-Aug-05", quantity:1575.9},
   {date:"23-Aug-05", quantity:1603.},
   {date:"24-Aug-05", quantity:1507.1},
   {date:"25-Aug-05", quantity:1568.8},
]);

private function getBarChartData(evt:MouseEvent):void{

 var title:String = "ASDFZXCVB";

 var pnlChart:Panel = new Panel();
 pnlChart.title = title;
 pnlChart.height = 750;
 {
  var categoryAxisDate:CategoryAxis = new CategoryAxis();
  categoryAxisDate.categoryField = "date";

  var linearVolumeAxis:LinearAxis = new LinearAxis();
  linearVolumeAxis.minimum = 1500;
  linearVolumeAxis.maximum = 1700;

  var colChart:ColumnChart = new ColumnChart();
  colChart.showDataTips = true;
  {

   var horizontalAxisDateRenderer:AxisRenderer = new AxisRenderer();
   horizontalAxisDateRenderer.axis = categoryAxisDate;
   horizontalAxisDateRenderer.placement = "bottom";

   var quantityRenderer:AxisRenderer = new AxisRenderer();
   quantityRenderer.axis = linearVolumeAxis;
   quantityRenderer.placement = "left";

   colChart.horizontalAxisRenderers.push(horizontalAxisDateRenderer);

   colChart.verticalAxisRenderers.push(quantityRenderer);

   {
    var quantityColumnSeries:ColumnSeries = new ColumnSeries();
    quantityColumnSeries.horizontalAxis = categoryAxisDate;
    quantityColumnSeries.yField="quantity";
    quantityColumnSeries.displayName ="QUANTITY";
    quantityColumnSeries.dataProvider = QUANTITY;
    quantityColumnSeries.verticalAxis = linearVolumeAxis;

    colChart.series.push(quantityColumnSeries);

   }

  }

  pnlChart.addChild(colChart);
 }

 canvasReportId.addChild(pnlChart);
}

]]>

           <mx:Button label="Submit" click="getBarChartData(event)"  x="293" y="4"/>
          </mx:Canvas>

A: try to add it with MXML like so:
<mx:ColumnChart id="chart" dataProvider="{QUANTITY}">
 <mx:horizontalAxis>
       <mx:CategoryAxis
            dataProvider="{QUANTITY}"
            categoryField="date"
        />
 </mx:horizontalAxis>
</mx:ColumnChart>

This worked for me...
Ladislav


text:
Q: ATMega168 UART weird characters I'm learning AVR programming using this book
I was able to run and get output using the code provided along with the book.
I use Proteus to simulate the output, since I don't have controller in hand.
Today I tried to write a simple UART program by using the data sheet.
/*
 * uart.c
 *
 * Created: 05-09-2018 09:55:36 PM
 * Author : New User
 */

#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
    UCSR0B = (1 << RXEN0) | (1 << TXEN0);
    UCSR0C = (1 << UCSZ01) | (1 << UCSZ00);
    UBRR0L = 6;
    char data;
    while (1)
    {
        while (!(UCSR0A & (1<<RXC0)));
        data = UDR0;
        while (!(UCSR0A & (1<<UDRE0)));
        UDR0 = data;

    }
}

When I simulate code in Proteus I get weird characters in the virtual terminal:

First I thought it might be due to an error in baud rate.
As my understanding, default F_CPU of ATMega168 is 1MHz if I don't use any external crystal oscillator. So for a baudrate of 9600, U0BRR = 6
from this equation:
U0BRR = (F_CPU/(16 * 9600)) - 1 = (1000000/16*9600)-1 = 5.51 ~6

Also in the datasheet, U0BRR is 6 for a baud rate 9600 with 1MHz clock.
So what's happening here?
IDE: AtmelStudio 7
Here's my Proteus settings:

Is there anything I should change in Proteus?

After checking the working code that came with the book, it uses a avr/setbaud.h header file.
If I add code from that header file, my current code will look like this(Instead of adding header file, I used entire code directly for better understanding)
#include <avr/io.h>
#define F_CPU 1000000UL

#ifndef BAUD
#define BAUD  9600
#endif

/* Baud rate tolerance is 2 % unless previously defined */
#ifndef BAUD_TOL
#  define BAUD_TOL 2
#endif

#ifdef __ASSEMBLER__
#define UBRR_VALUE (((F_CPU) + 8 * (BAUD)) / (16 * (BAUD)) -1)
#else
#define UBRR_VALUE (((F_CPU) + 8UL * (BAUD)) / (16UL * (BAUD)) -1UL)
#endif

#if 100 * (F_CPU) > \
  (16 * ((UBRR_VALUE) + 1)) * (100 * (BAUD) + (BAUD) * (BAUD_TOL))
#  define USE_2X 1
#elif 100 * (F_CPU) < \
  (16 * ((UBRR_VALUE) + 1)) * (100 * (BAUD) - (BAUD) * (BAUD_TOL))
#  define USE_2X 1
#else
#  define USE_2X 0
#endif

#if USE_2X
/* U2X required, recalculate */
#undef UBRR_VALUE

#ifdef __ASSEMBLER__
#define UBRR_VALUE (((F_CPU) + 4 * (BAUD)) / (8 * (BAUD)) -1)
#else
#define UBRR_VALUE (((F_CPU) + 4UL * (BAUD)) / (8UL * (BAUD)) -1UL)
#endif

#if 100 * (F_CPU) > \
  (8 * ((UBRR_VALUE) + 1)) * (100 * (BAUD) + (BAUD) * (BAUD_TOL))
#  warning "Baud rate achieved is higher than allowed"
#endif

#if 100 * (F_CPU) < \
  (8 * ((UBRR_VALUE) + 1)) * (100 * (BAUD) - (BAUD) * (BAUD_TOL))
#  warning "Baud rate achieved is lower than allowed"
#endif

#endif /* USE_U2X */

#ifdef UBRR_VALUE
   /* Check for overflow */
#  if UBRR_VALUE >= (1 << 12)
#    warning "UBRR value overflow"
#  endif

#  define UBRRL_VALUE (UBRR_VALUE & 0xff)
#  define UBRRH_VALUE (UBRR_VALUE >> 8)
#endif

int main(void) {

    UBRR0H = UBRRH_VALUE;
    UBRR0L = UBRRL_VALUE;
    #if USE_2X
    UCSR0A |= (1 << U2X0);
    #else
    UCSR0A &= ~(1 << U2X0);
    #endif
    /* Enable USART transmitter/receiver */
    UCSR0B = (1 << TXEN0) | (1 << RXEN0);
    UCSR0C = (1 << UCSZ01) | (1 << UCSZ00);   /* 8 data bits, 1 stop bit */

    char data;

    // ------ Event loop ------ //
    while (1) {
        while (!(UCSR0A & (1<<RXC0)));
        data = UDR0;
        while (!(UCSR0A & (1<<UDRE0)));
        UDR0 = data;
    }                                                  /* End event loop */
    return 0;
}

There's a variable called BAUD_TOL which is given a value as allowed tolerance from specified baud rate i.e., 9600
First it will calculate U0BRR value using this equation
U0BRR = (F_CPU/(16 * 9600)) - 1
==>U0BRR = (1000000/(16*9600))-1

this is the portion where it calculates U0BRR
#define UBRR_VALUE (((F_CPU) + 8UL * (BAUD)) / (16UL * (BAUD)) -1UL)
This will give U0BRR = 6 then uses this value to calculate baud rate(This is our calculated baud rate) and compare it with the baud rate wanted(9600). If difference is more than allowed one (BAUD_TOL), it will set USE_2X = 1.
As per datasheet

Bit 1 – U2Xn: Double the USART Transmission Speed This bit only has
  effect for the asynchronous operation. Write this bit to zero when
  using synchronous operation. Writing this bit to one will reduce the
  divisor of the baud rate divider from 16 to 8 effectively doubling the
  transfer rate for asynchronous communication.

Then recalculate U0BRR using
U0BRR = (F_CPU/(8 * 9600)) - 1
==>U0BRR = (1000000/(8*9600))-1

See 16 from previous equation changed to 8.
Then it will check whether it has a deviation of more than 2%. If there's it will trigger error or warning.
And in the main() function it will set U2X0 of UCSR0A to 1
So above code can be further reduced to
#include <avr/io.h>
#define F_CPU 1000000UL

#define BAUD  9600

#define UBRR_VALUE (((F_CPU) + 4UL * (BAUD)) / (8UL * (BAUD)) -1UL)

#define UBRRL_VALUE UBRR_VALUE

int main(void) {

    // -------- Inits --------- //
    UBRR0L = UBRRL_VALUE;
    UCSR0A |= (1 << U2X0);
    UCSR0B = (1 << TXEN0) | (1 << RXEN0);
    UCSR0C = (1 << UCSZ01) | (1 << UCSZ00);

    // ------ Event loop ------ //
    char data;
    while (1) {

        while (!(UCSR0A & (1<<RXC0)));
        data = UDR0;
        while (!(UCSR0A & (1<<UDRE0)));     /* Wait for incoming data */
        UDR0 = data;
    }
    return 0;
}

I have some doubts about this. About the way the code check baud rate is with in the acceptable range and what is the final baud rate after enabling U2X
I don't know whether I can ask it here.


text:
Q: Xamarin.Forms ios WebViewRenderer compartilhando Cookies Estou utilizando um WebViewRenderer para configuração a política de cookies e também para compartilhar cookies de um request de login de um HTTPClient. Acontece que por mais que eu dê o set:
 var cookieJar = NSHttpCookieStorage.SharedStorage;
   cookieJar.AcceptPolicy = NSHttpCookieAcceptPolicy.Always;
Ao depurar o no simulador do iphone e executar o webview é indicado no browser que a política de cookies não está habilitado, sendo assim o usuário não consegue fazer o login pois o webview executa um iframe de um ambiente seguro. Abaixo está o código:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Foundation;
using UIKit;
using Xamarin.Forms;
using Projeto.Custom;
using Projeto.iOS.Renderers;
using Xamarin.Forms.Platform.iOS;
using WebKit;
using System.IO;
using System.Net;

[assembly: ExportRenderer(typeof(CustomWebView), typeof(CustomWebViewRenderer))]
namespace Mynamespace.iOS.Renderers
{
    public class CustomWebViewRenderer : ViewRenderer<CustomWebView, WKWebView>
    {

        protected override void OnElementChanged(ElementChangedEventArgs<CustomWebView> e)
        {
            base.OnElementChanged(e);

            if(Control == null)
            {
                var userController = new WKUserContentController();
                var config = new WKWebViewConfiguration {
                UserContentController = userController };
                var webView = new WKWebView(Frame, config);
                SetNativeControl(webView);
            }

            if(e.OldElement != null)
            {
                var hybrid = e.OldElement as CustomWebView;
                hybrid.Cleanup();
            }

            if(e.NewElement != null)
            {
                var baseUrl = new NSUrl(NSBundle.MainBundle.BundlePath,
                true);
                string content = Element.Uri;
                Control.LoadHtmlString(content, baseUrl);

                var cookieUrl = new
                Uri("https://secure.gooddata.com/gdc/account/login");
                var cookieJar = NSHttpCookieStorage.SharedStorage;
                cookieJar.AcceptPolicy = NSHttpCookieAcceptPolicy.Always;
                foreach (var aCookie in cookieJar.Cookies)
                {
                    cookieJar.DeleteCookie(aCookie);
                }

                var jCookies =
                CustomCookie.CookieContainer.GetCookies(cookieUrl);
                IList<NSHttpCookie> eCookies =
                    (from object jCookie in jCookies
                     where jCookie != null
                     select (Cookie)jCookie
                     into netCookie
                     select new NSHttpCookie(netCookie)).ToList();
                cookieJar.SetCookies(eCookies.ToArray(), cookieUrl, cookieUrl);

            }
        }
    }
}

Se alguém puder me indicar qual é a melhor maneira de ativar a politica de cookies no WebView nativo do ios, agradeço desde já.

A: Bom depois de quebrar a cabeça, consegui resolver simplesmente troquei o  WKWebView por UIWebView. O que parece é que o WKWebView está com bug para acessar o NSHttpCookieStorage.SharedStorage, conforme essa discussão aqui Veja
Portanto é só substituir no ViewRenderer o WKWebView por UIWebView e tudo funciona perfeitamente. Notei no desempenho também o UIWebView demonstra ser mais rápido, no meu caso estou carregando um HtmlString com um iframe incorporado com dezenas de gráficos e o UIWebView, demonstrou ser superior.


text:
Q: Question about right-handed coordinate system The following question is from the book 'Calculus Two' by Flanigan/Kazdan:
Prove the following assertion: suppose that $X, Y$ and $Z$ are linearly independent. Then $X, Y$ and $Z$ is a right-handed coordinate system if and only if $Z$ and $X \times Y$ lie on the same side of the plane spanned by $X$ and $Y$.
Hint: this last part is difficult because it requires a formulation of a definition of "same side", and then an appropriate use of it.
So I have to show that $\langle X \times Y, Z \rangle > 0$ iff $Z$ and $X \times Y$ lie on the same side of the plane specified. Specifically, as the hint predicts, I don't know how to formulate a definition of "same side". If anyone knows how, I'd be very grateful. Thanks in advance.

A: Geometrically, a typical definition is:

*

*If $H$ is a plane and $P,Q$ are two points not lying on $H$, then $P$ and $Q$ lie on the same side of $H$ if and only if the line segment $\overline{PQ}$ does not intersect $H$

Algebraically, if $H$ is the plane through points $X$, $Y$, and the origin, then in my opinion a more convenient characterization is

*

*$P$ and $Q$ lie on the same side of the plane if and only if $ \operatorname{det}(P, X, Y)$ and $\operatorname{det}(Q, X, Y) $ have the same sign

Alternatively, the determinants can be expressed by triple products; e.g. $\operatorname{det}(P, X, Y) = P \cdot (X \times Y)$.
You can argue this really does capture the notion of "same side" by noting:

*

*$\operatorname{det}(R, X, Y)$ is continuous in $R$

*$\operatorname{det}(R, X, Y)$ takes both positive and negative values

*$\operatorname{det}(R, X, Y)$ is zero if and only if $R$ lies on $H$

so the sign of this function really does separate the complement of $H$ into two disconnected parts.

Another common algebraic definition is to let $N$ be a normal vector to $H$, and then define

*

*$P$ and $Q$ lie on the same side of $H$ if and only if $P \cdot N$ and $Q \cdot N$ have the same sign.


text:
Q: Alguém pode me da uma noção de como faço Modele computacionalmente a representação do funcionamento de uma
lâmpada, em que é possível acender, apagar e verificar se a lâmpada está
acessa.
Fiz isto:
class Lampada {

  boolean aceso = true;

  void apaga() {
    aceso = false;
  }

  void acende() {
    aceso = true;
  }

  boolean estaApagada() {
    if (aceso == false) {
      return true;
    }
    else {
      return false;
    }
  }

}

A: A classe parece pronta, mas uma melhoria pode ser feita no método estaApagada():
  boolean estaApagada() {
    return !aceso;
  }

Isso retornará o oposto da variável aceso, que é exatamente o status esperado pelo método.
Há outras coisas que podem ser melhoradas, como o fato de você não definir uma visibilidade mais restrita a variavel aceso. Ora se ela precisa de dois métodos para que seja alterada, não convem deixá-la com um possivel acesso externo, adicionando private você restringe o acessi direto a ela.
Outro detalhe citado pelo @Douglas e que faz total sentido é o enunciado pedir para que seja verificado se a lampada está acesa, e seu método verifica se está apagada. Embora também seja possível fazer essa verificação com o método criado, o método parece incoerente em relação ao solicitado no enunciado. A correção é tão simples quanto o método atual, basta retornar a própria variavel aceso.
A classe com as sugestões aplicadas ficaria assim:
class Lampada {

    private boolean aceso = true;

    public void apaga() {
       aceso = false;
    }

    public void acende() {
        aceso = true;
    }

    public boolean estaAceso(){

        return aceso;
    }
}

Deixo abaixo alguns links aqui do proprio site que podem te ajudar a aprender mais sobre conceitos basicos do java e de orientação a objeto:
Qual é a diferença entre modificadores public, default, protected e private?
O que são os conceitos de coesão e acoplamento?
Programação Funcional e Programação Orientada a Objetos. O que são e quais suas principais diferenças?


text:
Q: Publish Visual Studio extension to marketplace.visualstudio.com with TFS build pipeline I need to publish a Visual Studio extension to VS market place through the TFS CI build pipeline. I found following article on publishing extension to market place using command line, is there any deployment task in TFS which can use for this?
Publish from the command line

A: You can use the Visual Studio Team Services Developer Tools for Build and Release tasks.
Make sure you generate the PAT with teh correct permissions. In order to publish extensions you'll need "Marketplace (Publish)", in order to install/share/query extensions you'll need further permissions. The required permissions are documented in the "Add Service" window.


text:
Q: How to find out if DST was effective for some date in Python? I have following data: geographical coordinates of the place and local date and time, not necessarily current, may point to some moment many years ago. I also may have non-DST time zone effective currently, at present time (but  not necessarily correct for the date and time of interest).
I want to find out whether DST was in effect in that location at that local time using Python. Any ideas how to do that? I was reading about package pytz, but could not find anything suitable in it to complete that.

A: I'm assuming you've already resolved the time zone itself - if not, there are really two problems in this one question:

*

*Finding a time zone ID from coordinates

*Determining if DST was in effect in a time zone at an arbitrary date/time

I'm not very familiar with Python, but given this documentation I believe you want the tzinfo.dst(dt) function, which will return timedelta(0) in standard time, and the difference between the standard offset and the wall offset in DST. You pass in the datetime you want to find the offset for.
Note that in the pytz library, there's an additional is_dst parameter which you can specify to resolve ambiguities, where a given local time occurs twice due to a "fall back" transition.

A: You'll need one of the solutions in How to get a time zone from a location using latitude and longitude coordinates? to identify the timezone that the given coordinates belongs to.
Once you have the timezone you can then use the solution at Is a specific timezone using DST right now? to determine if DST is effective given the timezone and the date/time.


text:
Q: Why does the text on my button not appear? I'm making a text editor and I'm adding a navbar but the text on FileBtn doesn't appear.
from tkinter import *

##############################################

# Constants
width = 800
height = 450

##############################################

# Window Creation
Window = Tk()
Window.geometry(F'{width}x{height}')
Window.title("TextWrite")

##############################################

# Navbar Creation
Navbar = Frame(Window, width = width, height = 25, bg = "#141414")
Navbar.place(x = 0, y = 0)

# File Options Creation

def OpenFileOptions():
    FileOptions.place(x = 0, y = 25)

FileBtn = Button(Window, width = 10, height = 25, text = "File", bg = "#171717", fg = "white", command = OpenFileOptions)
FileBtn.place(x = 0, y = 0)

FileOptions = Frame(Window, width = 10, height = 50)
FileOptions.place(x = -1000, y = 0)

##############################################

# Text Input Creation
Input = Text(Window, width = width, height = 425, bg = "#202020", fg = "white")
Input.place(x = 0, y = 25)

Window.mainloop()

I searched for my problem but nothing I found seemed to fix it.
This is the first time I have encountered this error, and I have no clue why it happens.

A: The main problem is that you've set the height of the button to 25 lines tall. The width and height for some widgets -- including buttons -- is in number of characters, not pixels. Tkinter will center the text in the widget, so the text was very far down and out of view.
You can actually see this if you remove the text widget. You'll see that the button is very tall and the button label is centered in the button but roughly in the middle of the widget. (note: the following screenshot was taken on a Mac, which doesn't support changing the background color of buttons)

If you remove the height attribute altogether or set height to 1, you'll see the text, though you might have to also change the colors.

If you're just now learning tkinter, I strongly encourage you to use pack and/or grid rather than place. There's a slight learning curve, but it's much easier to make GUIs that are responsive and that make optimal use of the window size. place is best for very unique circumstances rather than as a general purpose tool.

A:
but the text on FileBtn doesn't appear

No need to change value. In line 37, change this y=25 to y=400. Should be like this: Input.place(x = 0, y = 400)
Screenshot:


text:
Q: Openmp do I have false sharing or Race condition? I'm learning Openmp, and I'm working on compressed sparse row multiplication (datatype std::complex<int>). And I'm getting different execution time each time I run the following function:
typedef std::vector < std::vector < std::complex < int >>> matrix;

struct CSR {
    std::vector<std::complex<int>> values; //non-zero values
    std::vector<int> row_ptr; //pointers of rows
    std::vector<int> cols_index; //indices of columns
    int rows; //number of rows
    int cols; //number of columns
    int NNZ; //number of non_zero elements
};

const matrix multiply_omp (const CSR& A,
    const CSR& B) {
    if (A.cols != B.rows)
        throw "Error";
    CSR B_t = sparse_transpose(B);
    matrix result(A.rows, std::vector < std::complex < int >>(B.rows, 0));
    #pragma omp parallel
    {
        #pragma omp for
        for (int i = 0; i < A.rows; i++) {
            for (int j = A.row_ptr[i]; j < A.row_ptr[i + 1]; j++) {
                int Ai = A.cols_index[j];
                std::complex<int> Avalue = A.values[j];
                for (int k = 0; k < B_t.rows; k++) {
                    std::complex < int > sum(0, 0);
                    for (int l = B_t.row_ptr[k]; l < B_t.row_ptr[k + 1]; l++)
                        if (Ai == B_t.cols_index[l]) {
                            sum += Avalue * B_t.values[l];
                            break;
                        }
                    if (sum != std::complex < int >(0, 0)) {
                        result[i][k] += sum;
                    }
                }
            }

        }
    }

    return result;
}

I set a for loop to call the function 10 iterations giving it 1000*1000 matrices and used omp_get_wtime(), and here is the result:
iteration 1 : 0.751642 s
iteration 2 : 0.911264 s
iteration 3 : 1.553695 s
iteration 4 : 0.761839 s
iteration 5 : 0.603688 s
iteration 6 : 0.423919 s
iteration 7 : 0.423114 s
iteration 8 : 0.445878 s
iteration 9 : 0.892305 s
iteration 10 : 0.918682 s

is that normal? or do I have false sharing or Race condition?


text:
Q: How can I get a worker thread to execute a callback on the main UI thread? I want to execute a number of tasks in parallel, once complete I want to execute a callback on the main UI thread. Is this possible? If so, how?

A: Multiple threading is not yet currenly supported, Its still under consideration, but there is support for parallel execution using Async await (just like in C#).
https://github.com/aspnet/Blazor/issues/139
https://github.com/aspnet/Blazor/issues/140


text:
Q: War file deployment I wrote a jsp application, and if I generate a war file with eclipse in windows XP, language: tradition Chinese. and deploy to weblogic,
it will have such problem:
inputAdministrator.jsp:251:11: This type name is ambiguous because it matches more than one '*'-import, including 'java.io.*' and 'admin.iguard.businessObject.*'.
                                        DataInput d = (DataInput) dataInput;
                                                                                ^-------^
inputAdministrator.jsp:252:29: Type java.io.DataInput contains no methods named getDept1.
                                            String dept1 = d.getDept1();
                                                                                ^------^
inputAdministrator.jsp:253:26: No match was found for method trim() in type <error>.
                                            String emp2 = d.getEmp2().trim();
                                                                                ^----------------^
inputAdministrator.jsp:253:28: Type java.io.DataInput contains no methods named getEmp2.
                                            String emp2 = d.getEmp2().trim();
                                                                                ^-----^
inputAdministrator.jsp:254:29: Type java.io.DataInput contains no methods named getDept2.
                                            String dept2 = d.getDept2();
                                                                                ^------^
inputAdministrator.jsp:255:33: Type java.io.DataInput contains no methods named getDept_code.
                                            String dept_code = d.getDept_code();
                                                                                ^----------^
inputAdministrator.jsp:256:32: Type java.io.DataInput contains no methods named getStaff_no.
                                            String staff_no = d.getStaff_no();
                                                                                ^---------^
inputAdministrator.jsp:257:32: Type java.io.DataInput contains no methods named getEmp2_por.
                                            String emp2_por = d.getEmp2_por();
                                                                                ^---------^

if I generate the war file in windows xp, simplize Chinese, and deploy to weblogic, everything will be OK.
I don't know how the "text file encoding" setting will affect the generated war file,
how can i make sure that all this things are in sync.
Any one have better solution?
Any suggestions will be appreciated.
Thanks in advance!

A: May be the "text file encoding" triggers some kind of recompilation which makes that issue visible.
In any case, could you try first to disambiguate the DataInput usage, by:

*

*adding for example "java.io."(in front of DataInput) everywhere in that source where it is actually a java.io case (leaving a simple DataInput for businessObject usages)

*not using import java.io.* (but using CTRL+SHIFT+O for reorganizing the imports)

would that solve the problem, whatever the "text file encoding" is?

A: did you check it? does text encoding changes in both the j2ee exports as a WAR file?
windows-->preferences-->General-->workspace-->textfileencoding?
it defaults to cp1532
what is the value of textfileencoding variable set in simplize Chinese as compared to tradition Chinese ??


text:
Q: How to make the 'int' to 'string' with special format?     int score=8;
    scoreLabel.text=[NSString stringWithFormat:@"%5d",score];

I want to make the scoreLabe show the text '00008',but when the line code was executing,the result is '8',can any one tell me how to make it?

A: try:
[NSString stringWithFormat:@"%05d", score]

A: NSString *numStr = [NSString stringWithFormat:@"%05d", yourNum];


text:
Q: cannot convert 'int (*)[4]' to 'int**' for argument '1' to 'void generaMatriz(int**, int, int)' He estado realizando este programa, y el único error que manda es sobre los apuntadores, de como es que estamos mandando y recibiendo las variables.
A es una matriz que se genera con números aleatorios.
La función mayorDirección devuelve una copia idéntica del dato mayor almacenado en una matriz y la posición en la que se encuentra dentro de la matriz
El código es el siguiente:
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <wchar.h>

#define orden 4

int** reservaMemoria(int filas, int columnas);
void liberaMemoria(int ** A, int filas, int columnas);
void generaMatriz(int** A, int filas, int columnas);
int  mayorDireccion(int** A, int filas, int columnas, int* filasMay, int* columnasMay);
void pintaMatriz(int** A,  int filas, int columnas);

int main ()
{
    int A[orden][orden], filas, columnas, Grande, filasMay, columnasMay;
    system("color 03");
    setlocale(LC_ALL, "");

    printf("Ingresa el número de filas: ");
    scanf("%d", &filas);
    printf("Ingresa el número de columnas: ");
    scanf("%d", &columnas);

    columnasMay = columnas;
    filasMay = filas;

    A = reservaMemoria(filas, columnas);
    generaMatriz(A, filas,columnas);

    Grande = mayorDireccion(A, filas, columnas, filasMay, columnasMay);

    system("cls");
    printf("La matriz es:\n");
    pintaMatriz(A, filas, columnas);

    printf ("Y el grande de la matriz es: %d", Grande);
    system("pause");

    liberaMemoria(A, filas, columnas);
    return 0;
}

void generaMatriz(int** A, int filas,int columnas)
{
    int i,j;

    for(i=0; i<filas; i++)
    {
        for(j=0; j<columnas; j++)
        {
            A[i][j] = rand()%10;
        }
    }
}

void pintaMatriz(int** A,  int filas,int columnas)
{
    int i, j;

    for (i=0; i<filas; i++)
    {
        for(j=0; j<columnas; j++)
        {
            printf("[%d] [%d] = %d \n", i, j, A[i][j]);
        }
    }
}

int** reservaMemoria (int filas,int columnas)
{
    int** pArreglo;
    int i;

    pArreglo = (int**)calloc(filas,sizeof(int*));

    if(pArreglo == NULL)
    {
        printf("Memoria insuficiente...");
        exit(-1);
    }

    else
    {
        for(i=0; i<filas; i++)
        {
            pArreglo [i] = (int*)calloc(columnas,sizeof(int));

            if(pArreglo[i] == NULL)
            {
                printf("Memoria insuficiente...");
                exit(-1);
            }
        }
    }

    return pArreglo;
}

void liberaMemoria(int ** A, int filas, int columnas)
{
    int i;

    for(i=0; i<filas; i++)
    {
        free(A[i]);
    }

    free(A);
}

int mayorDireccion(int** A, int filas,int columnas, int* filasMay, int* columnasMay)
{
    int i, j;
    int may;

    may=A[0][0];
    *filasMay=0;
    *columnasMay=0;

    for(i=0; i<filas; i++)
    {
        for(j=0; j<columnas; j++)
        {
            if(A[i][j]<may)
            {
                may = A[i][j];
                *filasMay=i;
                *columnasMay=j;
            }
        }
    }

    return may;
}

Quisiera saber cual es la solución más óptima para seguir usando apuntadores en el algoritmo anterior. Sería de gran ayuda (:

A: Si declaramos un array tal que:
int A[2][2] = {{ 1, 2 }, { 3, 4 }};

Nos encontraremos que todos los valores de la matriz acaban ubicados en posiciones contiguas de memoria:
  00   01   02   03
|  1 |  2 |  3 |  4 |

El compilador debe conocer en todo momento las dimensiones del array para poder calcular la posición de cada elemento.
Sin embargo, un puntero doble funciona de forma diferente. En este caso, la variable almacena una dirección de memoria. Lo que vamos a encontrar en esta dirección de memoria son más direcciones de memoria. Estas últimas direcciones ya sí apuntarán a enteros. Es decir, sería algo tal que:
   0x00    0x01        0x100 0x101        0x200 0x201
| 0x100 | 0x200 | ... |  1  |  2  | ...  |  3  |  4  |

Como ves, la estructura en memoria cambia radicalmente y de ahí que el compilador te muestre un error.
La solución pasa por usar estructuras de datos compatibles. O usas arrays o usas punteros dobles. Tienes que elegir una de las dos soluciones, ya que no puedes mezclarlas.
Mi opinión personal sería usar punteros. Los arrays son estructuras con poco recorrido debido principalmente a varios factores:

*

*Se almacenan en la pila del programa. La pila tiene un tamaño muy limitado y, si se llena, el programa muere.

*No se puede modificar su tamaño de ninguna manera

*Al estar en la pila, debes que tener cuidado con los punteros que lo referencien. No vaya a ser que el array se destruya y los punteros se queden apuntando a memoria que ahora pertenece a otras variables


text:
Q: Functional test in Symfony 3.3 with fake user I wanna test my application created in Symfony 3.3.2.I'm using FOSUserBundle as my users system.
I create a new client in setUp
public function setUp() {
    $this->client = static::createClient();
}

I wrote a simple function that should create fake user by fos service
private function logInAdmin() {
    $fosLoginManager = $this->client->getContainer()->get('fos_user.security.login_manager');

    $user = new User();
    $user->setEnabled(true);
    $user->addRole('ROLE_ADMIN');

    $fosLoginManager->logInUser('main', $user);
}

Actually this is happening but only when I testing this code manually in controller. In this case I'm logged as user whose I just created in code. I have my roles etc. But when PHPUnit run this code, the user becomes null.
Why this is happening? How to do it correctly?

A:    <?php

namespace AdminBundle\Security;

use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;

class LoginTest extends WebTestCase
{

    /**
     * @var Client
     */
    private $client = null;

    protected function setUp()
    {
        $this->client = static::createClient();

    }
    private function logIn()
    {
        $session = $this->client->getContainer()->get('session');

        // the firewall context defaults to the firewall name
        $firewallContext = 'main';

        $token = new UsernamePasswordToken('admin', null, $firewallContext, array('ROLE_ADMIN'));
        $session->set('_security_'.$firewallContext, serialize($token));
        $session->save();

        $cookie = new Cookie($session->getName(), $session->getId());
        $this->client->getCookieJar()->set($cookie);
    }

    public function testLoginToBackOffice()
    {
        $this->logIn();
        $crawler = $this->client->request('GET', '/admin');
        $response = $this->client->getResponse();
        $this->assertSame(Response::HTTP_OK, $response->getStatusCode());
        //200 means i am logged in else should be a redirection to the login path
    }

}

I use for my tests sqlite3 as database layer,here is what i put in my config_test.yml
doctrine:
  dbal:
    driver: pdo_sqlite
    path:     "%kernel.cache_dir%/db"
    charset: UTF8

And before running functionnals tests, i build a db with the schema and some fixtures.
php bin/console doctrine:database:drop --force --env=test
php bin/console doctrine:database:create --env=test
php bin/console doctrine:schema:create --env=test
php bin/console doctrine:fixtures:load --env=test -n

Inside the fixture i create an admin user.
I just did this now the test is passed.


text:
Q: How to fix an invalid certificate? Followed a guide to make my portfolio website. It never used to say this but as of last week it started to say my certificate isn't valid. Also curious why the image on the tab shows the "wix" icon? I didn't use wix to create this..
invalid certificate


text:
Q: invalid quotes in find call In my project
`
$cid = $this->Surgical->find('first',array('conditions' =>
 array('to_char(dt_surgery , \'DD-MM-YYYY\' )' =>'to_char(now() ,\'DD-MM-YYYY\')')));

In debug mode the query equals the following:=
SELECT "Surgical"."id"   FROM "surgicals" AS "Surgical"   WHERE to_char(dt_surgery , 'DD-MM-YYYY' ) = 'to_char(now() ,''DD-MM-YYYY'')'  LIMIT 1
My problem is unwanted quotes at 'to_char(now() ,''DD-MM-YYYY'')' i.e at begin and at end. Also there is double quotes at  ''DD-MM-YYYY''
My db is Postgres and cake version is 1.3.
Actually I want the following 'where' condition inside the select query
WHERE to_char(dt_surgery , 'DD-MM-YYYY' ) = to_char(now() ,'DD-MM-YYYY') LIMIT 1

A: Did you try this? Notice line 3 does not have ' => ' but just =
$cid = $this->Surgical->find('first', array(
    'conditions' => array(
        'to_char(dt_surgery , \'DD-MM-YYYY\') = to_char(now() ,\'DD-MM-YYYY\')'
     )
 ));


text:
Q: Image size on Objective-C How to get Image size in Objective-C.
I loaded one image using imagePicker, I want know the size of that image. (w*h)
is it possible?
Thanks & regards...

A: You implement the UIImagePickerControllerDelegate Protocol and in particular the imagePickerController:didFinishPickingMediaWithInfo: method. The last parameter in that method is a dictionary that includes an UImage references by the UIImagePickerControllerOriginalImage key. Get this UIImage* and get it's size property.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    UIImage *image = (UIImage*) [info objectForKey:UIImagePickerControllerOriginalImage];
    //access width and height like this
    image.size.width;
    image.size.height;
}


text:
Q: Windows and Ubuntu Dual Boot both broken due to update I'm facing a huge problem: Ubuntu had some updates to do. After installing the updates I couldn't boot Ubuntu due to this error :
"Failed to open \EFI\ubuntu\grubx64.efi - Invalid Parameter
Failed to load image \EFI\ubuntu\grubx64.efi - Invalid Parameter
start_image() return Invalid parameter, falling back to default loader

Then I found a solution online saying that I should run this command below under windows :
bcdedit /set {bootmgr} path \EFI\ubuntu\grubx64.efi

After executing and restarting the computer I keep getting this error when booting to windows now:
 "Failed to open \EFI\ubuntu\??S - Invalid Parameter
Failed to load image \EFI\ubuntu\??S - Invalid Parameter
start_image() return Invalid parameter, falling back to default loader

So both of my OS are now broken and I don't have a bootable device anymore. What can I do to fix this? I tried repairing with OS Support Recovery but still did not work...
Does anyone have a fix for this issue please.


text:
Q: How to set boundary condition in a complex soap film GAM smoother? I am modelling the distribution of bottlenose dolphins in the lagoon of a South Pacific Island. I would like to use a soap-film smoother to model the probability of dolphin presence over a 2D surface (longitude x latitude) accounting for land boundaries (as obviously dolphins cannot go on land).
I woukd like to know how to fix the boundary of my study area (land and offshore waters) to a condition equal to zero, as I am expecting to have a null probability of finding a dolphin on land, as well as in the most offshore waters of my study area (this species of dolphin is only found in lagoon shallow waters). So far, I have tested several approaches that I will describe below, but the maps predicted by my models do not follow my expectations as to how the boundary condition should be handled.
Here is what the dataset looks like when mapped. Dolphin locations are shown in blue, while absence locations are shown in pink. The land is shown in black and the reefs delineating the lagoon in grey.

Step 1: create the boundary and knots objects
I created a boundary polygon called soap_bnd, converted it to a list of lists called bound and filled it with knots soap_knots. The boundary includes two inner "holes" that are formed by two islands found in the study area. The following code was inspired by: Gavin Simpson's excellent blogpost https://www.fromthebottomoftheheap.net/2016/03/27/soap-film-smoothers/ and https://journals.plos.org/plosone/article/file?type=supplementary&id=info:doi/10.1371/journal.pone.0205921.s001
I use the function autocrunch created by David L Miller (see https://github.com/dill/soap_checker).
Positions are in a projected UTM coordinate system (hence the coordinate columns are called utmx and utmy)
## boundary of the soap film (one polygon with two inner loops)
# soap_bnd is initially a SpatialPolygonDataFrame
crds <- tidy(soap_bnd)
crds <- crds %>% dplyr::select(long, lat, piece)
names(crds) <- c("x", "y", "piece")
bound <- split(crds, crds$piece)
bound <-lapply(bound,`[`, c(1, 2))
nr <- seq(1, 3)
bound <-lapply(nr, function(n) as.list.data.frame(bound[[n]]))

## bound is a list of 3 lists (because 1 large polygon and 2 loops), each including 3 elements (utmx, utmy and f)
## an element f is set to a vector of zeros to set the boundary condition
bound <- lapply(nr, function(n) bound[[n]] <- c(bound[[n]], list(f = rep(0, length(bound[[n]]$x)))))

## created a grid of knots within the boundary
soap_knots <- make.soapgrid(bound[[1]][c("x", "y")], 20)

# removing the knots that overlap with the inner loops (the islands)
x <- soap_knots$x
y <- soap_knots$y
soap_knots <- soap_knots[!inSide(x = x, y = y, bnd = bound[[2]]) &
                           !inSide(x = x, y = y, bnd = bound[[3]]),]

# just changing names so everything matches
bound <- llply(bound, function(b){names(b)[1:2] <- c("utmx", "utmy"); return(b)})
names(soap_knots) <- c("utmx", "utmy")

# remove points too close to the boundary
crunch_ind <- autocruncher(bound, soap_knots, k = 20, xname = "utmx", yname = "utmy")
soap_knots <- soap_knots[-crunch_ind, ]

## plotting the final product
plot(soap_bnd)
points(soap_knots)

Step 2: run the GAM
The GAM model is binomial as I am modeling the distribution of dolphin locations (1) with other locations from which dolphins were absent (0).
m1.1 <- mgcv::gam(response ~
                    s(utmx, utmy, bs = "so", xt = list(bnd = bound)),
                    knots = soap_knots,
                    family = binomial, method = "REML",
                    data = target_df)

# predict the probability of presence using a raster stack called envLS_stack (which includes other environmental variables which are not used here)
pred_ras <- raster::predict(envLS_stack[[c("utmx", "utmy")]], m1.1, type = "response")

# plot the predictions - included between zero (low probability of presence) and one (high probability of presence)
plot(pred_ras, col = rev(brewer.pal(11, "Spectral")), axes = F)

Tests and issues
Here is the probability of dolphin presence (lands and offshore waters in white).

I don't understand why the probability on the boundaries turns out being the highest although I set the f boundary to zero.
I tried another approach where I removed the f elements in my bound lists. I rerun the GAM with the following code:
bound_nof <- llply(bound, function(d){list(utmx = d$utmx, utmy = d$utmy)})

# I tried this model with k = 20 or k = 60
m1.2 <- mgcv::gam(response ~
                    s(utmx, utmy, k = 20, bs = "so", xt = list(bnd = bound_nof)),
                    knots = soap_knots,
                    family = binomial, method = "REML",
                    data = target_df)

And here is what I get, respectively when using k=20 and k=60:

I cannot figure out what is going on here? In the first map (k=20) it looks like the model strongly picked up on a single dolphin observation made to the extreme west part of the study area and produced a big patch of high probability of presence there... statistically speaking I do not think this pattern is relevant. The second map (k=60) is even more puzzling...
I imagine this pattern may be due to a lack of data to the west and south of my study area. Is it necessary to reduce the size of the finite area where the soap-film is produced? The drawback is that this would prevent any further extrapolation of the model to the larger area I am interested in.


text:
Q: binding a client to a local port I am trying to configure my TCP client to use a specific local port to connect to another TCP server.
I am using the code below but it doesnt' work.
Do you know what I am doing wrong and if this is possible?
I am using LINUX machine.
Thanks
AFG
    int localport=32000;
    m_clientfd = socket( AF_INET, SOCK_STREAM, 0 );
    assert( m_clientfd >= 0 );

    // someone set the localport
    struct sockaddr_in sa_loc;
    struct hostent* pLocalHostInfo = gethostbyname( "localhost" );
    long LocalHostAddress;
    memcpy( &LocalHostAddress, pLocalHostInfo->h_addr
    , pLocalHostInfo->h_length );

    // Local
    memset(&sa_loc, 0, sizeof(struct sockaddr_in));
    sa_loc.sin_family = AF_INET;
    sa_loc.sin_port = htons(localport);
    sa_loc.sin_addr.s_addr = LocalHostAddress;
    int ret_bind = bind(m_clientfd, (struct sockaddr *)&sa_loc
    , sizeof(struct sockaddr));
    assert( ret_bind != -1 );

A:
int ret_bind = bind(m_clientfd, (struct sockaddr *)&sa_loc,
    sizeof(struct sockaddr));

The last argument should be sizeof(sa_loc) or sizeof(struct sockaddr_in).

A: It looks that using the code below make the app working. It was enough to remove the setup of the local IP.
// Local
memset(&sa_loc, 0, sizeof(struct sockaddr_in));
sa_loc.sin_family = AF_INET;
sa_loc.sin_port = htons(localport);
// sa_loc.sin_addr.s_addr = LocalHostAddress; // COMMENT THIS TO WORK
int ret_bind = bind(m_clientfd, (struct sockaddr *)&sa_loc
, sizeof(struct sockaddr));
assert( ret_bind != -1 );


text:
Q: Jquery with Json and PHP Hi i have post form in jquery with php , the form call other page and get the result with json from jquery , for example when i use jquery and call to this page in php i get this for read json from jquery :
<?php
print '{"login":"datos_fails_lock"}';
?>

The problem in this case it´s i can only show this and no include other text in the results , if include more os this code the script no works , i like json detect this code but also i want show html and at the moment i can´t do this
It´s posible when i call other page from form of jquery i can include other informations as html and works json from this page
Sorry i explain the best i can
Regards !

A: Instead of printing your own json text layout, why not use PHP json_encode to do it for you. that way you can have the array you want including html and have that function encode it.
Example:
<?php
print json_encode(array('login' => 'datos_fails_lock'));
?>

A: At the PHP side:
<?php
  // compute html
  $html = '

...

';
  // compute json
  $json = '{"login":"datos_fails_lock"}';

  $response = array('html' => $html, 'json' => $json);
  print json_encode($response);
?>

At the JavaScript side:
var response = JSON.parse( xhr.responseText );

// append html to a div
$( '#response' ).html( response.html );
// parse json response
var jsonObj = JSON.parse( response.json );

A: To the best I can understand,
if you are looking to get json encoded values from your php file and show with jquery that called the file you do something like:
In you php file:
<?
  echo json_encode(array(
    'login' => 'datos_fails_lock',
    'something_else' => 'Other thing'
  ));
?>

and from jQuery if it is post submission, you can use some thing like:
$.post('ajax/process.php', function(data) {
  $('.result').html(data.login);
  $('.other_thing').html(data.something_else);
});

A: The best inline solution:
<?php
    $myObjectOrArray = (object) array('test' => array('test' => array('test' => 'testValue')));
    $javascriptGateway = rawurlencode(json_encode(myObjectOrArray));
?>

I use this solution so I can pass my php object containing special char into a javascript object.


text:
Q: Transparent regions of a BufferedImage are writing out black I know this is something to do with compositing but I can't work out what. In an earlier section of code, a particular list of pixels in a BufferedImage are set to be transparent black:
        for(Pixel p : closed){
            Color c = new Color(image.getRGB(p.x, p.y));
            Color newC = new Color(0,0,0, 0);
            image.setRGB(p.x, p.y, newC.getRGB() & 0x00000000);
        }

        if(andCrop){
            image = image.getSubimage(left, top, right-left, bottom-top);
        }

        return image;

Then I attempt to write the image out:
try {

            BufferedImage out = new BufferedImage(image.getWidth(), image.getHeight(), java.awt.Transparency.TRANSLUCENT);
            Graphics2D g2d = out.createGraphics();
            g2d.setComposite(AlphaComposite.Clear);
            g2d.fillRect(0, 0, image.getWidth(), image.getHeight());
            g2d.setComposite(AlphaComposite.Src);
            g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
            g2d.dispose();

            File outputfile = new File(file);
            ImageIO.write(out, "png", outputfile);
        } catch (IOException e) {

        }

Now, I know that 'out' is clear before I attempt to draw the image onto it. What I'm not getting is what's wrong with my compositing. Instead of coming out as transparent, I'm getting full-black.
All bufferedimages used are INT_ARGB.
EDIT - This has been solved. The image source was from ImageIO.read and the BufferedImage returned did not support alpha. A quick post-read conversion let the rest of the code run smoothly.

A: Things that comes to my mind... (thanks to Andrew):
java.awt.Transparency.TRANSLUCENT = 3
TYPE_INT_ARGB = 2
TYPE_INT_ARGB_PRE = 3

public BufferedImage(int width,
                 int height,
                 int imageType)

Constructs a BufferedImage of one of the predefined image types. (TYPE_...)

http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/image/BufferedImage.html
so it seems as basically it's a mixup.
Besides, what is the effect you want to achieve? you clear an empty image, then draw fully transparent pixels to it... I just don't get it.

A: Whelp, this has been downvoted now so I'm not sure this will be relevant, but the issue was that the original BufferedImage was being read in by ImageIO, and this image was not supporting ARGB. A quick post-read conversion allowed the rest of the code to work.


text:
Q: XAML Page constructor I have a Silverlight 4 application.
What would cause the Constructor in my codebehind file to be called more than once?
Currently I suspect it gets called when I set the datacontext or do applytemplate.
I can see it when I debug the application and I put a breakpoint on the first line in my constructor, BUT it does not give me a stacktrace.
Thanks

A: I discovered that the MainPage.xaml.cs file can have a {usercontroname}_Loaded event.
I moved my method call that started the database query to that event instead of the constructor.
Works like a charm now.

A: the constructor should only be called once per control instance. Is your control maybe used more than once in your app? Or maybe a page that includes the control is instantiated more than once?
Cheers, Alex


text:
Q: ImportError: liblapack.so.3gf: cannot open shared object file: No such file or directory I have both python 2.7.16 and python 3.5.2 installed on my ubuntu 16.04 LTS and numpy used to work well on both of them but recently something went wrong with numpy on python 2 while it still running smoothly on python 3
I have tried to uninstall and install the numpy package and this did not fix anything
The exact stdout I am getting is as follow:
python -c "import numpy as np"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/home/ahmed/.local/lib/python2.7/site-packages/numpy/__init__.py", line 153, in <module>
    from . import add_newdocs
  File "/home/ahmed/.local/lib/python2.7/site-packages/numpy/add_newdocs.py", line 13, in <module>
    from numpy.lib import add_newdoc
  File "/home/ahmed/.local/lib/python2.7/site-packages/numpy/lib/__init__.py", line 18, in <module>
    from .polynomial import *
  File "/home/ahmed/.local/lib/python2.7/site-packages/numpy/lib/polynomial.py", line 19, in <module>
    from numpy.linalg import eigvals, lstsq, inv
  File "/home/ahmed/.local/lib/python2.7/site-packages/numpy/linalg/__init__.py", line 50, in <module>
    from .linalg import *
  File "/home/ahmed/.local/lib/python2.7/site-packages/numpy/linalg/linalg.py", line 29, in <module>
    from numpy.linalg import lapack_lite, _umath_linalg
ImportError: liblapack.so.3gf: cannot open shared object file: No such file or directory

A: Indeed Linux error while loading shared libraries: cannot open shared object file: No such file or directory resolved the problem. I had have only to do the following:
sudo find / -iname liblapack.so.3gf
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:*path_to_lib_as_found*
sudo ldconfig -v

Thanks to Abdur Rehman for the hint
Cheers.

A: Does your Ubuntu have the latest lapack library? Try installing sudo apt install liblapack3gf liblapack-dev. Sometimes you need to run sudo ldconfig after the install.