text:
Q: Array for tableview returning 0 My app is a fake messaging app for kids. They "send a message", and that segues to a message sent screen. When the message sent screen shows, it triggers a timer that delays a reply being created and added to an array, which will then be used to populate the "inbox" table. Using nslog, the timer runs, the method runs, the array is populated. But when I nslog the number of rows (being the result to array.count) it is logging 0. I've spent the afternoon trying to get the code working but I'm obviously missing something. I've even tried moving the "logic code" for creating the array to its own file to separate that and the table methods but it achieves the same result.
The problem is that repliesArrayForTable in inbox table.m is returning null. But it nslogs the name as it should in inbox repliesMethod, and even if I create an instance of inbox in inboxTable and set it that way via view did load and repliesArrayForTable = inboxInstance.allReplies it still returns null.
@implementation inbox

@synthesize allReplies, childsName;

-(void)timerForOtherMethods {

        NSLog(@"populate array timer");
    NSTimer *timer = [NSTimer timerWithTimeInterval:6 target:self selector:@selector(repliesMethod) userInfo:nil repeats:NO];
    NSLog(@" add timer");
    [[NSRunLoop mainRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];

}

-(NSMutableArray *)repliesMethod {

NSMutableArray *replies = [[NSMutableArray alloc]init];

    [replies addObject:childsName]; // childsName set in messageSent
    NSLog(@" replies array includes: %@", replies); //logs name

    InboxTable *inboxTable = [[InboxTable alloc]init];
    inboxTable.repliesArrayForTable = replies; //logs as should

    return allReplies = replies;

}

@implementation InboxTable

static NSString *CellIdentifier = @"Cell Identifier";

@synthesize repliesArrayForTable;

- (void)viewDidLoad {
    [super viewDidLoad];

}

-(void)viewWillAppear:(BOOL)animated {

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    NSLog(@"replies in array: %lu", (unsigned long)repliesArrayForTable.count);   // logs 0?
    return [repliesArrayForTable count];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    cell.textLabel.text = @"From Sorting Office";

    return cell;
}

@end

A: Try this:
inboxTable.repliesArrayForTable = [replies mutableCopy]; //logs as should

return allReplies = [replies mutableCopy];

If that doesn't do the trick then move your inboxTable instance outside your repliesMethod.


text:
Q: Cannot query field "me" on type "Query".GraphQL: Validation Getting this error when trying to use my query. Everything is fine in graphql playground just running into this issue with my app. I;m new to graphql (if it wasnt obvious already) so let me know if there's anything else I need to show.
I've tried uninstalling and re-installing graphql-tag to no luck.
Here is where my error currently is
import { Query } from "react-apollo";
import gql from "graphql-tag";

const CURRENT_USER_QUERY = gql`
  query {
    me {
      id
      name
      email
    }
  }
`;

const User = props => (
  <Query {...props} query={CURRENT_USER_QUERY}>
    {payload => props.children(payload)}
  </Query>
);

export default User;

my schema
type Query {
  users(query: String): [User!]!
  me: User
}

my resolver
const Query = {
  me(parents, args, { request, prisma }, info) {
    if (!request.userId) {
      return null;
    }
    return prisma.query.users(
      {
        where: { id: request.userId }
      },
      info
    );
  }

export { Query as default };

Should be getting back an individual user.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to calculate the string 'yyyymm' into the string 'yyyymm -1' ex: calculate '201401' into '201312' in T-SQL? How to calculate  the string 'yyyymm' into the string 'yyyymm -1'
Ex: calculate  '201401' into '201312' in T-SQL?

A:  declare @x char(6) = '201401'
 select convert(char(6), dateadd(month, -1, @x + '01'), 112)


text:
Q: ANT parameter passing by reference
I am very new to ANT scripting and am using it for automating daily build's in my project. I am using it more in the sense of scripting (XML files) and aggregate pre-existing features and come up with build process.
I feel I have some basic understanding problem with the antcall/target concept. Especially when antcall is made with parameter, Like C++, is there a way to call target will parameter as  pass by reference? so that value changed in the target can be retrieved by the caller?
In the below example, I want to check if two files are same and display the result, but for the below example, I would get the output as

Are Same Files : ${isFileName}

Example:
< target name="checkFileAreSame">
< condition property="isFileSame">
< filesmatch file1="a.txt" file2="b.txt"/>
< /condition >
< /target >
< target name="Maintask">
< antcall target="checkFileAreSame">
< param name="isFileSame" value="false">
< /antcall >
< echo message="Are files Same : ${isFileSame}"/>
< /target >

Thanks for your input in advance.

A: Ant properties are immutable - once set, their values cannot be changed.
When using the antcall task note that:

The called target(s) are run in a new
  project; be aware that this means
  properties, references, etc. set by
  called targets will not persist back
  to the calling project.

But also note that the properties that you pass to the called target using 'antcall' param attributes are immutable in the called target.
That means that in the 'condition' task example given:
<condition property="isFileSame">
    <filesmatch file1="a.txt" file2="b.txt"/>
</condition>

the isFileSame property is already set to false by the caller, and so will remain false regardless of the file comparison.
It's more common to declare dependencies between targets in this sort of way:
<target name="checkFileAreSame">
    <condition property="isFileSame">
        <filesmatch file1="a.txt" file2="b.txt"/>
    </condition>
</target>

<target name="Maintask" depends="checkFileAreSame">
    <echo message="Are files Same : ${isFileSame}"/>
</target>

Ant will determine the call graph for 'Maintask' requires that 'checkFileAreSame' be run first.

A: It sounds like you need AntCallBack task from ant-contrib package (separate from core Ant).
Ant-contrib is a very useful library if you aren't happy (like many) with Ant's "declarative" flow style.
See here:
http://ant-contrib.sourceforge.net/
http://ant-contrib.sourceforge.net/tasks/tasks/index.html
http://ant-contrib.sourceforge.net/tasks/tasks/antcallback_task.html


text:
Q: Divs should not overlap I have a small problem. The webpage I'm working on has three areas:

*

*On the left a navigation, which should always be on the left side

*A content area in the middle, which should always be in the middle of the browser

*The logo area on the right side, which should always be in the top right corner

Here's the code I have right now:
CSS
html, body
    {
        height: 100%;
        min-height:100%;
        padding: 0em;
        margin: 0em;
    }

body
{
    font-family: Segoe UI, Arial;
    font-size: 12px;
    color: #616a71;
    line-height: 15px;
    letter-spacing: 0.5px;
    overflow-y: scroll;
    background-color: #CCC;
}

div#navigation
{
    position: absolute;
    float: left;
    width: 220px;
    left: 5px;
    top: 70px;
    z-index: 2;
    padding-bottom: 50px;
    background-color: red;
}

div#content
{
    position: relative;
    width: 1014px;
    margin: 0 auto;
    top: 70px;
    padding: 10px;
    background-color: #f6f6f3;
    box-shadow: 0 0 5px rgba(0,0,0,0.2);
    border-radius: 2px;
    line-height: 20px;
}

div#right
{
    position: absolute;
    width: 258px;
    right: 0;
    top: 0;
    background-color: green;
}

HTML
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=9" />
    <title>header</title>
    <link href="/style/test.css" rel="stylesheet" type="text/css" media="screen" />

        nav

        content

        logo

Now, when I resize the browser, the content area goes behind the navigation are. What I want to achieve, is that when there is too little space to display the navigation and content area side by side the horizontal scrollbar of the browser should appear.

A: By using the CSS media queries as the ones specifies below
@media (max-width: 600px) {
 // Your code goes here
}

You can specify the CSS to be used for these widths. Change the width accordingly

A: Try to give the width of divs as %.
div#navigation
{
    width: 20%;
}

div#content
{
    width: 60%;
}

div#right
{
    width: 20%;
}

and float them all to left.


text:
Q: Infinite recursion when trying to build a resolution solver in prolog in prolog I am trying to build a resolution solver in prolog. My program works fine when I use primary connectives, but there is infinite recursion when I try to add secondary connectives(equivalence, not equivalence). To be more specific when I run:
clauseform(a equiv b, L).

I get:
L = [[neg a, b], [neg b, a]]

But when I run:
test(a equiv b).

program enters into infinite recursion.
This is what I have:
?-op(140, fy, neg).
?-op(160, xfy, [and, or, imp, revimp, uparrow, downarrow, notimp, notrevimp]).
?-op(180, xfy, [equiv, notequiv]).

/* member(Item, List) :- Item occurs in List */
member(X, [X | _]).
member(X, [_ | Tail]) :- member(X, Tail).

/* remove(Item, List, Newlist) :- Newlist is the result of removing all occurences
                                  of Item from List */

remove(_, [], []).
remove(X, [X | Tail], Newtail) :- remove(X, Tail, Newtail).
remove(X, [Head | Tail], [Head | Newtail]) :- remove(X, Tail, Newtail).

/* conjunctive(X)  :- X is an alpha formula. */

conjunctive(_ and _).
conjunctive(neg(_ or _ )).
conjunctive(neg(_ imp _)).
conjunctive(neg(_ revimp _)).
conjunctive(neg(_ uparrow _)).
conjunctive(_ downarrow _).
conjunctive(_ notimp _).
conjunctive(_ notrevimp _).
conjunctive(_ equiv _).
conjunctive(neg(_ notequiv _)).

/* disjunctive(X) :- X is a beta formula */

disjunctive(neg(_ and _)).
disjunctive(_ or _).
disjunctive(_ imp _).
disjunctive(_ revimp _).
disjunctive(_ uparrow _).
disjunctive(neg(_ downarrow _)).
disjunctive(neg(_ notimp _)).
disjunctive(neg(_ notrevimp _)).
disjunctive(neg(_ equiv _)).
disjunctive(_ notequiv _).

/* unary(X) :- X is a double negation, or a negated constant */

unary(neg neg _).
unary(neg true).
unary(neg false).

/* components(X, Y, Z) :- Y and Z are the components of the formula X,
                          as defined in the alpha and beta table. */

components(X and Y, X, Y).
components(neg(X and Y), neg X, neg Y).
components(X or Y, X, Y).
components(neg(X or Y), neg X, neg Y).
components(X imp Y, neg X, Y).
components(neg(X imp Y), X, neg Y).
components(X revimp Y, X, neg Y).
components(neg(X revimp Y), neg X, Y).
components(X uparrow Y, neg X, neg Y).
components(neg(X uparrow Y), X, Y).
components(X downarrow Y,neg X, neg Y).
components(neg(X downarrow Y), X, Y).
components(X notimp Y, X, neg Y).
components(neg(X notimp Y), neg X, Y).
components(X notrevimp Y, neg X, Y).
components(neg(X notrevimp Y), X , neg Y).
components(X equiv Y, X imp Y, Y imp X).
components(neg(X equiv Y), neg(X imp Y), neg(Y imp X)).
components(X notequiv Y, neg(X imp Y), neg(Y imp X)).
components(neg(X notequiv Y), X imp Y, Y imp X).

/* component(X, Y) :- Y is the component of the unary formula X. */

component(neg neg X, X).
component(neg true, false).
component(neg false, true).

resolve(neg neg X, X).
resolve(X, X).

/* singlestep(Old, New) :- New is the result of applying a single step of the
                           expansion process to Old, which is a generalized
                           conjunction of generalized disjunctions. */

resolutionstep([Disjunction | Rest], New) :-
    member(Formula, Disjunction),
    unary(Formula),
    component(Formula, Newformula),
    remove(Formula, Disjunction, Temporary),
    Newdisjunction = [Newformula | Temporary],
    New = [Newdisjunction | Rest].

resolutionstep([Disjunction | Rest], New) :-
    member(Beta, Disjunction),
    disjunctive(Beta),
    components(Beta, Betaone, Betatwo),
    remove(Beta, Disjunction, Temporary),
    Newdis = [Betaone, Betatwo | Temporary],
    New = [Newdis | Rest].

resolutionstep([Disjunction | Rest], New) :-
    member(Alpha, Disjunction),
    conjunctive(Alpha),
    components(Alpha, Alphaone, Alphatwo),
    remove(Alpha, Disjunction, Temporary),
    Newdisone = [Alphaone | Temporary],
    Newdistwo = [Alphatwo | Temporary],
    New = [Newdisone, Newdistwo | Rest].

resolutionstep([Disjunction | Rest], [Disjunction|Newrest]) :-
    resolutionstep(Rest, Newrest).

/* expand(Old, New) :- New is the result of applying singlestep as many
                       times as possible, starting with Old. */

resolution(Con, Newcon) :-
    resolutionstep(Con, Temp),
    resolution(Temp, Newcon).

resolution(Con, Con).

/* dualclauseform(X, Y) :- Y is the dual clause form of X. */
/* change later from neg X to X */

clauseform(X, Y) :- resolution([[X]], Y).

closed([Branch | Rest]) :-
    member(false, Branch),
    closed(Rest).

closed([Branch | Rest]) :-
    member(Y, Rest),
    select(X, Branch, B),
    resolve(neg X, L),
    select(L, Y, Y2),
    append(B, Y2, Rest0),
    sort(Rest0, Rs),
    remove(Y, Rest, Rest1),
    append([Rs], Rest1, FRest),
    write('FRest: '), write(FRest), nl,
    sort(FRest, Result),
    write('Resul: '), write(Result), nl,
    closed(Result).

closed([[]]).

/* if_then_else(P, Q, R) :- either P and Q, or not P and R */
if_then_else(P, Q, _) :- P, !, Q.

if_then_else(_, _, R) :- R.

test(X) :-
    resolution([[neg X]], Y),
    if_then_else(closed(Y), yes, no).

yes :- write('YES'), nl.

no :- write('NO'), nl.

I am suspecting that the problem is in this block of code:
closed([Branch | Rest]) :-
        member(Y, Rest),
        select(X, Branch, B),
        resolve(neg X, L),
        select(L, Y, Y2),
        append(B, Y2, Rest0),
        sort(Rest0, Rs),
        remove(Y, Rest, Rest1),
        append([Rs], Rest1, FRest),
        write('FRest: '), write(FRest), nl,
        sort(FRest, Result),
        write('Resul: '), write(Result), nl,
        closed(Result).

How can I fix it?


text:
Q: Azure Container Instance : Container creation issue I am currently trying to create a new container on Azure Container Instance, to deploy a .net core app image on it. (I'm a newbie on this techno).
I have created a Container Registry on Azure and pushed an image on it (.net fore Console Application).
I have tried to create a container from Azure Portal, but continuously get the same error:

"code": "InaccessibleImage", "message": "The image
  '/emulator' in container group
  'flow-emulator-container' is not accessible. Please check the image
  and registry credential."

So I have decided to try the creation from Azure CLI. I can login to Container Registry without problem. But when I try to create the container with the following command, I still have the same error, and I have no Idea how to troubleshot it...
In PowerShell:
az container create --resource-group Flow --name flow-emulator --image <ContainerRegistry.azurecr.io>/emulator --cpu 1 --memory 1 --registry-login-server <ContainerRegistry.azurecr.io> --registry-username <username> --registry-password <password> --dns-name-label flow-emulator-container --ports 80 --os-type windows

A: For your issue, according to you said that you can log in to the Container Registry without a problem, then I think the most possible reason is you need to add a tag that you need to use for your image.
For example, your command should be like this:
az container create --resource-group Flow --name flow-emulator --image <ContainerRegistry.azurecr.io>/emulator:tag --cpu 1 --memory 1 --registry-login-server <ContainerRegistry.azurecr.io> --registry-username <username> --registry-password <password> --dns-name-label flow-emulator-container --ports 80 --os-type windows

You can choose an available tag for your image. By the way, you'd better make sure the username and password are really right again even if you check it before.


text:
Q: Azure API Gateway: Remove a attribute label from json In azure api gateway i want to remove "content":
from below example
From this
{
  "content": {
    "product": "apple",
    "productcode": "12345566",
    "details": [
      {
        "issuedId": 16294,
        "IssuesTo": "CAND",
        "Description": "Replacement",
        "created": "2016-02-24T05:51:56",
        "occurred": "2016-02-24T05:49:47.000EST",
        "IssuedBy": "James"
      }
    ]
  }
}
to this
{
    "product": "apple",
    "productcode": "12345566",
    "details": [
      {
        "issuedId": 16294,
        "IssuesTo": "CAND",
        "Description": "Replacement",
        "created": "2016-02-24T05:51:56",
        "occurred": "2016-02-24T05:49:47.000EST",
        "IssuedBy": "James"
      }
    ]
  }
I have tried searching most of the recommendations are to serialize the object in the code. Can i do the same through Azure API gateway if yest how. Please can some one guide me to right direction.
Thanks,

A: There is no support for this functionality out of the box in Azure API Management, Unfortunately.
MSDN documentation lists all possible policies that can be used in Azure API Management, and none of them can perform this task.
The possible workaround is to use a service to translate this JSON. An Azure function or LogicApp maybe.

A:
Here's a very simple solution:

You can create a simple logical flow through the LogicApps designer on Azure.
I created one taking your sample JSON request body and specifying the response JSON to match what you were looking for and I got it running pretty easily. I tested it out with postman by sending HTTP POST with the sample request JSON to the URL that LogicApps will provide you when you design one. I only used the Request and Response triggers and actions and nothing else.

The LogicApp flow should look like:

When I tested through postman, I sent your JSON as my HTTP POST and I
  got the response JSON in the desired format:


text:
Q: Mistake with insertion sort realisation in C Here is my code
#include <stdio.h>

int main(void){

    int unsorted[] = {1,3,4,5,2};
    int i = 0;
    int j = 0;
    int temp = 0;
    for(i = 1; i <= 5; i++){
        temp = unsorted[i];
        j = i - 1;
        while(unsorted[j] > unsorted[i]){
                unsorted[i] = unsorted[j];
                unsorted[j] = temp;
            }

}
        for(i = 0; i < 5; i++){
        printf("%i", unsorted[i]);
    }
    return 0;
}

The output is 13425. It's entering the while loop enough times to move the 2(the last element) to its place, but for some reason it isn't.

A: I found 3 mistakes
#include <stdio.h>

int main(void){

    int unsorted[] = {1,3,4,5,2};
    int i = 0;
    int j = 0;
    int temp = 0;
    for(i = 1; i <= 5; i++){
        temp = unsorted[i]; // You are out of array boundaries here
        j = i - 1;
        while(unsorted[j] > unsorted[i]){
            // you need to place j-th element in (j+1)-th
            // position, but not in i-th position
            unsorted[i] = unsorted[j];
            unsorted[j] = temp; // you can do this one time after end of this cycle
            // You need to decrement j in this cycle until j >= 0
        }

    }
    for(i = 0; i < 5; i++){
        printf("%i", unsorted[i]);
    }
    return 0;
}

A: Try like this:
#include <stdio.h>
int main(void){

    int unsorted[] = {1,3,4,5,2};
    int i = 0;
    int j = 0;
    int temp = 0;
    for(i = 1; i < 5; i++){
        j = i;
        while(j>0 && unsorted[j]<unsorted[j-1]){
                temp = unsorted[j];
                unsorted[j] = unsorted[j-1];
                unsorted[j-1] = temp;
                j--;
            }

}
    for(i = 0; i < 5; i++){
    printf("%d", unsorted[i]);
}
return 0;

}


text:
Q: Getting undefined is not an object (evaluating 'navigation.push') when calling a component inside of another Here is my component:
function MyHeader({navigation}){

    let cartPress = () => navigation.push("Cart");

    return(
        <View>
            <TouchableOpacity onPress={cartPress}>
                <Text>Cart</Text>
            </TouchableOpacity>
        </View>
    );

}

export default MyHeader;

When I call it in the following component:
import React from 'react';
import MyHeader from "../MyHeader";

function MyScreen({navigation}){
    return(
        <View>
            <MyHeader />
        </View>
    );

}

export default MyScreen;

I am getting the following error in the MyScreen component:

TypeError: undefined is not an object (evaluating 'navigation.push').

However when I call what's in the MyHeader component without calling the AppHeader component, I do not get that error:
import React from 'react';
import MyHeader from "../MyHeader";

function MyScreen({navigation}){
    let cartPress = () => navigation.push("Cart");

    return(
        <View>
            <TouchableOpacity onPress={cartPress}>
                <Text>Cart</Text>
            </TouchableOpacity>
        </View>
    );

}

export default MyScreen;

What is the problem ?

A: You didn't pass the navigation property to the <MyHeader /> component, try: <MyHeader navigation={navigation} />


text:
Q: Forcing separation of content in two columns I've been using the multicol package lately because I was trying to typeset content in two columns and I like minimalist solutions.
However I've been having trouble trying to force content to stay in one of the two columns only. But I've seen this behavior occurring:

*

*If the left column is shorter than a page, using \columnbreak is enough and it will force the rest of the content to the right column. For example: How do I force a column-break in a multi-column page?

*If the content is longer than a page, though, using this command won't bring any results (except for the last page/part of the content). The command is ignored, and the first column will use the second until the first condition is satisfied again, i.e. the content is shorter than a page.

How can I force the content to stick to the first (left) column until \columnbreak (or a similar command) is issued and only then start at the top of the second column? Or am I using the wrong package for this sort of task?

A: You can try the paracol package.
Example:
\documentclass{article}

\usepackage[latin]{babel}  %only for the example
\usepackage{lipsum}        %only for the example

\usepackage{paracol}

\begin{document}

\begin{paracol}{2}

  \lipsum[1-2]

  \lipsum[1-2]

  \switchcolumn

  \lipsum[1-2]

\end{paracol}

\end{document}

Output:

You might also take a look at the CTAN topic parallel where you can find similar packages.


text:
Q: Discrete superharmonicity The value at $(n,m)$ of the "Discrete Laplace operator" (see wikipedia) of a function $f$ in $\Bbb Z\times \Bbb Z$ is $\Delta f(n,m)=  \frac{1}{4}( f(n+1,m)+f(n,m+1)+f(n-1,m)+f(n,m-1))-f(n,m)$:
the difference between the average of $f$ at the $4$ next points and the value of f at $(n,m)$.
If $g\in C^2(\Bbb R^2)$ we can set
$f_\varepsilon (n,m)=g(x+n\varepsilon,y+n\varepsilon)$, then when $\varepsilon\downarrow 0$, $ f_\varepsilon\to g$ and  $\Delta f_\varepsilon\to\Delta g$ the usual Laplacian. Usual harmonic ($\Delta g=0$) and subharmonic
($\Delta g\geq 0$) functions in $g\in C^2(\Bbb R^2)$  when upper-bounded are constant.

Question 1 Upper-bounded discrete harmonic functions $f$ in $\Bbb Z\times \Bbb Z$ are constant? (I have done that)
Question 2 Is that still true for discrete sub-harmonics? (I could not do that but might be in some paper).

Judgments about the banality of the questions are welcome if preceded by their solutions or references.


text:
Q: Restricting the size of data structure being created My header file is
typedef struct vector vector;

vector * vector_create(size_t size);

The c file:
vector * vector_create(size_t size){
    if(size >= PTRDIFF_MAX)
        return NULL;
    //actual creation logic
}

I need to restrict the size of the vector to be no more than PTRDIFF_MAX since I need to subtract pointers to one vector element from the other. The problem comes when I want to test it
void test_create_vector_too_large(void){
#if SIZE_MAX >= PTRDIFF_MAX + 1
    list * lst = list_create(((size_t) PTRDIFF_MAX) + 1);
    assert(!lst);
#endif
}

This code produce tons of warnings
/home/kjroff/main.c:55:32: warning: integer overflow in preprocessor expression
 #if SIZE_MAX >= PTRDIFF_MAX + 1
                                ^
/home/kjroff/main.c:55:29: warning: the right operand of ">=" changes sign when promoted
 #if SIZE_MAX >= PTRDIFF_MAX + 1

The intention of the #if macro was to check if the upper limit of ptrdiff_t exceeds upper limit of size_t. In case they are the same this test does not make sense. But it does in case PTRDIFF_MAX < SIZE_MAX.
How to write such an assertion correctly?

A: The comparison is generally useless, as size_t and ptrdiff_t are typically the same width but size_t is unsigned and ptrdiff_t is signed, so SIZE_MAX is necessarily greater than PTRDIFF_MAX. This is not strictly specified by the C standard, as size_t is merely the type used for size expressions and is, in spite of intent, not explicitly specified to be sufficient to represent the size of any object. Similarly, ptrdiff_t is merely the type used for differences of pointers and is, in spite of intent, not explicitly specified to be sufficient to represent the differences of all pointers.
That said, you can change the comparison to SIZE_MAX > PTRDIFF_MAX, which is equivalent, as pointed out by pmg. Another way to quiet the warnings is to change 1 to 1u, yielding SIZE_MAX > PTRDIFF_MAX + 1u. Per C 2018 6.10.1 4, in preprocessing, the integer types behave as if they were intmax_t and uintmax_t, so 1u has the type uintmax_t, so PTRDIFF_MAX will be converted to uintmax_t, then added to 1u (which will not overflow), and the comparison will be between two uintmax_t types (avoiding a warning).
The question states "I need to restrict the size of the vector to be no more than PTRDIFF_MAX since I need to subtract pointers to one vector element from the other." But the unit of a size_t is one byte, and the unit of a ptrdiff_t is one array element. Unless the vector type is a single byte, the result of subtracting two vector * pointers will be scaled down. Even in constrained systems where size_t struggles to cover all the possible sizes, ptrdiff_t should comfortably have room for the differences of two vector * pointers, regardless of the size of the underlying array. So the test if(size >= PTRDIFF_MAX) seems useless.

A:
How to write such an assertion correctly?

Instead of
#if SIZE_MAX >= PTRDIFF_MAX + 1

Subtract (SIZE_MAX is at least 65535) so no overflow possible.
#if SIZE_MAX - 1 >= PTRDIFF_MAX

or simply use > @pmg
#if SIZE_MAX > PTRDIFF_MAX


text:
Q: Asymptotic notation: A function is Θ-Notation H. Cormen, Exercise 3.1-2
The following statement is true? If yes, prove that it is true.
$$
(n+a)^b = Θ(n^b)\\
a, b \in R\\
b>0
$$

I tried to expand $(n+a)^b$ using the Binomial theorem, but I couldn't solve this.
Any help?

A: Notice that
$$\lim_{n\to +\infty}\frac{(n+a)^b}{n^b}=1,$$
hence there is some $n_0$ for which if $n\geqslant n_0$,
$$\frac 12 n^b\leqslant (n+a)^b\leqslant \frac 32 n^b.$$
This proves that for some $M$, the inequality
$$\frac 1M\leqslant \frac{(n+a)^b}{n^b}\leqslant M$$
holds for each $n\geqslant 1$.
More generally, if $(a_n)_{n\geqslant 1}$ and $(b_n)_{n\geqslant 1}$ are two sequences of positive numbers such that $(a_n/b_n)_{n\geqslant 1}$ converges to a positive number, then $a_n=\Theta(b_n)$.

A: for $n>a \ (n+a)^b = (n(1+\frac{a}{n}))^b = O(n^b) \cdot O(1)$. From this you can easily deduce the lower bound.


text:
Q: Absolute Positioning Issue I can't find a title for this because it's a complicated issue.
Let's say i have this:

I Can Control This DIV

I CANNOT control this DIV

Is there any way for the first div to reserve it's area and the 0px should be beneath it.
I mean i want the second div to stay beneath the first div like it's inside an iframe BUT i don't want to use iframes or frames at all.
Any way? i don't have a prob if it's Javascript solution.
Thanks

A: You can enclose second div in position:relative container. This way, top:0px will be counted from that div and not the whole window:
http://jsfiddle.net/z9KbD/
Explanation is in definition of position:absolute: Generates an absolutely positioned element, positioned relative to the first parent element that has a position other than static.

A: Can you wrap both of them in another div and them control that one?

A: If you give the second div a clear:both, that should do the trick I think you are looking for. Essentially, it will act as a carriage return for that div.
On a side note, if you were looking to absolutely position an element, you will need a parent element that contains it to be relatively positioned. Chris Coyier goes over it in depth here.


text:
Q: Android Studio an array in onStop() why does the program crash at "String temp_str = string_array[1]" ?
Logcat: java.lang.NullPointerException: Attempt to read from null array.
public class MainActivity extends AppCompatActivity {
public String string_array[];

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String string_array[]=new String[10];

    string_array[1]="word1";
    string_array[2]="word2";
    string_array[3]="word3";

}

@Override
protected void onStop(){
    super.onStop();

    String temp_str = string_array[1];

}

}

A: You have defined String string_array[] twice. Once in class scope and once in onCreate() method.
For intended behavior, delete the declaration inside onCreate()
For example, delete this line inside onCreate()
String string_array[]=new String[10];

A: Program crash because you are declaring localy (in onCreate()) second variable with name string_array[] and you initialize only this one variable. Your global variable public String string_array[] isn't initialized anywhere so is null.
To make this code working you should delete declaration in onCreate() and move initialization to global variable declaration:
public class MainActivity extends AppCompatActivity {
public String string_array[] = new String[10];

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    string_array[1]="word1";
    string_array[2]="word2";
    string_array[3]="word3";

}

@Override
protected void onStop(){
    super.onStop();

    String temp_str = string_array[1];

   }
}

A: Delete this line in onCreate():
String string_array[]=new String[10];

In class scope use this declaration:
public String[] string_array = new String[10];

And delete this one:
public String string_array[];


text:
Q: How to configure base url for all requests using HTMX? Given example from the docs
  <button hx-post="/clicked"
       hx-trigger="click"
       hx-target="#parent-div"
       hx-swap="outerHTML">
    Click Me!
  </button>

I want to change <scheme>://<netloc>/clicked to<scheme>://<netloc>/api/v1/clicked, so  prepend /api/v1 into the base URL so all requests use this version. How to do that?

A: The only solution I can think of is to just alter the event path.
            <script>
                document.body.addEventListener('htmx:configRequest', (event) => {
                    event.detail.path = `/api/v1/${event.detail.path}`
                })
            </script>


text:
Q: About Approval Process Urgent 1) I want to know about ProcessInstance , ProcessInstanceSteps and ProcessInstanceWorkItem   what is relation among them and when a record is sent for approval then I think some records are created but by don't records are created for which sobject.
2) Also want to know what is ActorId and OrignalActorId.
3) how can I find, how many records have approved by a user.
Advance thank

A: 1) ProccessInstance is parent of ProcessInstanceSteps and ProcessInstanceWorkItem. ProcessInstanceSteps  stores the steps followed by approvers (one or more) e.g; accept, reject  or reassign. Comments, ActorId and OriginalActorId etc., all these saved in ProcessInstanceSteps. It is created for each new step taken by approver.  And information like OriginalactorId, (parent) processInstanceId etc are saved in ProcessInstanceWorkItem. It mostly used for pending approvals.
2) OriginalactorId is the first person who is authorized to take action on record and actorId is the person who is currently assigned (In several steps actorId changes and when reassign OriginalActorId changes). ActorId and OriginalActorId also available in ProcessInstanceWorkItem.
3) By query from ProccessInstance to child ProcessInstanceSteps  you can get who approved/rejected the record. ProccessInstance can be used to get status of record and on which sObject.
For more details about fields, start reading from here

A: I don't know how your implemented your approval process but here is what use :
List<ProcessInstance> processInstances = [select Id, Status, TargetObjectId,
                                                //that's the Approval History in your page layout
                                                (select ActorId, Comments, ProcessInstanceId, OriginalActorId, StepStatus from Steps order by CreatedDate asc)
                                        from ProcessInstance where TargetObjectId = 'your_record_id'];

System.debug('+---------$ Your record['+processInstances[0].Steps[0].TargetObjectId+'] is submitted');
System.debug('+---------$ Submitter : '+processInstances[0].Steps[0].OriginalActorId);
System.debug('+---------$ Approver : '+processInstances[0].Steps[0].ActorId);

I didn't really check if the syntax is correct but should be something like that.


text:
Q: Different footer versions in Community Builder I need to create a different footer for one of our page. The only difference is the disclaimer language. How is this achieved? Currently, the footer is shared throughout the site.

A: The solution was to check the "Override the default theme layout for this page" button which is located all the way down on the Page Properties tab pane.


text:
Q: protractor loading or referring to 3rd party JS library in the test I am using the protractor to test the angular js application and I have used those 3rd party JS in the application.
I have used a fusion chart, charts js and a few more.
to test those in the protractor spec file
var env = require('C:/DSP/lab/fusion_chart_testing/test/fusioncharts-suite-xt-latest/js/fusioncharts.js');
describe(' chart ', function() {
it('chart', function() {

    browser.get("http://127.0.0.1:3000/WebContent/project.html");

    expect('false').toBeTruthy();

});

});
am trying to use those JS but it's giving me an error " Error: ReferenceError: document is not defined"
the reason is in protractor its element(....).
do i need to change in 3rd party JS or any other way to load this 3rd part js and use them in test.


text:
Q: `No Access-Control-Allow-Origin` header is present - AngularJS So, when I looked up the error, I see mostly it has something to do with with the webservice.
The problem is that I cant touch the webservice. However, using Postman extension on chrome it returns data just fine. So, i tend to believe that there is something wrong on frontend.
Also, Im using angular and rather at beginner's level, so I might be missing something trivial.
.factory('forecast', ['$http', function($http){

    return $http.get('https://link')
        .success(function(data) {
            return data;
        })
        .error(function(err) {
            return err;
        });
   }
]);

A: You will always get the Access-Control-Allow-Origin error if the webservice you are trying to access via REST doesn't have that header set for the response you are aiming to get.
However, most of the times, you can get around it by making a Server -> Server request instead of a Client -> Server (AJAX) request.
For example, if you are using NodeJS as a backend and make the request from there, then send the response back to your client via Node, you should be fine.
EDIT: Also, as stated in the comments (forgot that, thanks), AngularJS's $http service also exposes a $http.jsonp method using which you can get around that. However that only works if the webservice you are trying to access also exposes the information as JSONP in their API.
Documentation on $http.jsonp


text:
Q: Highcharts show the same yAxis start and end value with multiple data series I'm trying to get both the left and right yAxis to show the same start and end.
Is it possible to show the same increment on yAxis with multiple data series? If so could you provide a sample code or point to an example. Here's what I'm trying to achieve.

Thank you in advance for your help!

A: Yes it is possible.  You can control the axis labels by using the same min, max, and tickInterval for both axis.  In the following example I use the following on both series:
min: 0,
max: 600,
tickInterval: 50,

A: Highcharts also has the functionality to link multiple axis together using the linkedTo attribute. All you have to specify in the properties of an axis is what axis it is linkedTo by specifying its index in the array of axes.
yAxis: [

                { // Primary
                    title: {
                        text: "Label for first Axis"
                    }
                },
                { // Dependent Axis
                    title:{
                        text: "Label for dependent Axis"
                    },
                    linkedTo: 0
                }
            ]


text:
Q: asp: open "save-as" dialog for PDF (using asppdf + xmlhttp) i'm using asp + asppdf (a component for creating pdf files).
asppdf has a method called SaveHTTP which causes the browser to open the "save-as" dialog for saving the pdf. so the component is sending the pdf as binary data to the browser.
my question: i'd like to load the pdf via xmlhttp + then open that dialog.
loading works (i'm getting the data) - but i'm not sure how to call the save-as dialog.
any ideas if it's possible?
thanks

A: You need to add a Content-Disposition: attachment header to the HTTP response.
EDIT: It is not possible to show a save dialog using AJAX.
Instead, you can set location.href to the PDF URL (with Content-Disposition: attachment), which will do what you're trying to accomplish.  (You could also POST a <form> in a hidden <iframe>)


text:
Q: How to get participants for a conversation in Twilio I'm using the Twilio Conversations Client for iOS. How do you get the participants for a conversation? Each conversation object has a participants array object.
[TwilioConversationsClient conversationsClientWithToken:token properties:nil delegate:self
    completion:^(TCHResult *result, TwilioConversationsClient *convoClient) {

    NSArray *participants = self.client.myConversations.firstObject.participants;

}];

How do you reload this array? I don't see any method like "getParticipants" to reload these values.
For instance, to reload the messages for a conversation there is this method.
- (void)getMessagesAfter:(NSUInteger)index
               withCount:(NSUInteger)count
              completion:(nonnull TCHMessagesCompletion)completion;

A: Twilio developer evangelist here.
That is odd that there isn't a method to reload the participants array. It exists within the JavaScript SDK, so I would have thought it would exist in the iOS SDK, but it doesn't for now.
So, the participants call you refer to is the way to get the initial list of participants after loading the conversation, then you should keep up with the participants that have joined and left the conversation using the participantJoined and participantLeft delegate methods.


text:
Q: Logo and menus are not aligned My problem is that I want the logo and ΛΟΓΙΣΜΙΚΟ menu to be aligned.
I've tried everything and I can't make them move together. The menus move a lot faster...
I'm trying with javascript to get the positions and set the logo to move with the same position as the menu but I can't figure it out here is the page http://www.altasoft.gr/index_.htm

.nav-container {
    background: #eaeaeb;
    /*background: #fff url(../images/menu_bg.gif) no-repeat 50% 0%;*/
    clear: both;
    height: 48px;
}
#nav {
    /*padding: 0px 0px 0px 30px;*/
    width: 931px/*920px*/;
}
#nav li {
    padding-right: 8px;
    margin-top: 10px;
    padding-bottom: 10px;
    text-decoration: none;
}

A:

A: Just change the width of the #nav
Screenshot:

A: hey actually you should follow the mentioned below code i hope this will work for you please change your header DIV code with my code :-
HTML

U have to remove the position property from your logo div and its position values top & left and just define the width:931px; with margin:auto and its working fine as per your requirement....


text:
Q: Is MongoDB causing my Ubuntu 10.04 root file system to be completely full? If so how can I uninstall MongoDB? A few days ago I decided to install MongoDB but, right after I installed it problems started happening. I outline exactly how I installed MongoDB and all the problems that ensued soon after at this post at AskUbuntu.com I do want to mention that I talked to one of the people on the #mongodb IRC channel and they told me that MongoDB needs like 10GB to run.

Could that be why my Ubuntu's root file system got full after MongoDB installation? Makes sense. If this is true and MongoDB is the issue, then how should I go about uninstalling MongoDB?
Also is there any way to keep MongoDB and save my Ubunutu 10.04? Or should I do a clean install of Ubuntu but give it more room thank just 10GB?
UPDATE 1
cd / && du -hcs *
8.4M  .... bin
34M   ..... boot
4.0K  ..... cdrom
625M  ... data
312K ...  dev
17M  ....  etc
45G  ....  home
0   ......... initrd.img
0    .........  initrd.img.old
275M ..  lib
13M ....   lib32
0   .........   lib64
16K .....   lost + found
3.9M ...  media
4.0K ....  mnt
442M ...  opt
0   ..........   proc
1.2M ....  root
7.3M ....  sbin
4.0K ....  selinux
204K ...  srv
0  ..........    sys
12K  ......  tmp
5.2G ....  usr
2.5G ....  var
0 ..........     vmlinuz
0 ..........     vmlinuz.old
54G ......   total
UPDATE 2
This is what happened when I tried to remove mongodb:
s3z@s3z-laptop:/$ sudo apt-get purge mongodb mongodb-server mongodb-clients mongodb-dev
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package mongodb is not installed, so not removed
E: Couldn't find package mongodb-server

This is strange because I can start up mongoDB's shell:
s3z@s3z-laptop:/$ mongo
MongoDB shell version: 2.0.2
connecting to: test
>

How come this is happening?

A: You can probably just run apt-get purge mongodb mongodb-server mongodb-clients mongodb-dev mongodb-10gen to remove almost all references to MongoDB and all its data. There will still be some references to MongoDB in the /var/lib/ and /var/log/ directories which can be deleted manually.
For future installs of MongoDB, you might want to put its home directory (and thereby its associated data) onto your /home partition, which still has plenty of free space. Heck, you could still move its data if you wanted. Up to you.

Do you have any idea how I could find out what is filling my disk up?

The easiest way is the du(1) command, which will report the disk used for files and directories.
du -mx / | sort -n | less

The last lines will be the directories that have taken up the most space. The -x keeps it on one file system -- I presume you don't care so much about /home yet. The -m reports output in megabytes; if you want output in kilobytes instead, use -k. (I figure if you're tracking down ten gigabytes of content, you'll want to look for megabytes.)

A: I depends on how mongodb was installed.  If you didn't install it via apt but perhaps via another download then apt couldn't uninstall it.  However its rare that an installer would remove application created data as part of its uninstall process.
Just run the Disk Usage Analyser (on the Applications -> Accessories menu) on your / folder to see where the space is being taken up.  Then perhaps you can backup and remove the file(s) in question.


text:
Q: Biztalk security groups As a prerequisite for BizTalk installation, there are security groups that need to be created and users put in those groups in active directory.
BizTalk Application Users
BizTalk Isolated Host Users
BizTalk Server Administrators
BizTalk Server B2B Operators .....

Some suggestions pointed out that those security groups need to be Global but my organization only allows us to create these groups within our OU.
So my question is if those groups are created within our OU only vs created as global group, will it have any negative implication/restriction to future BizTalk operations?
Please advise.

A: I don't think there's a problem here.  BizTalk Groups should be Global type, as opposed to Universal or Local.  But, you can create Global Groups in an Organization Unit defined in AD.
Meaning, Global is a type of Group, not the scope of the Group.


text:
Q: I want two functionalities together I want to have 2 buttons on the product view page one will just add product to cart and it will not redirect it to cart. However other will add product to cart and also redirect the user to cart. So please guide me how this can be achieved.

I am adding my code here please check
<button type="button" class="button" onClick="addcart(this.id);productAddToCartForm.submit(this);redirectcart();"  id="buyitnowid">
             <?php echo $this->__('BUYNOW'); ?>
        </button>

Java script is
productAddToCartForm.submit = function(button, url) {
        if (this.validator.validate() &&  !addOptions.submittedForm) {
            var form = this.form;
            var url = form.action;

            if (weltpixel.quickview.inIframe) {
                parent.weltpixel.quickview.addToCart(url, $(form).serialize(true), addOptions);
            } else {
                weltpixel.quickview.addToCart(url, $(form).serialize(true), addOptions);
            }

            addOptions.submittedForm = true;
        } else {
            jQuery('html,body').animate({
                scrollTop: jQuery("#product-options-wrapper").offset().top -100
            });
        }
    }.bind(productAddToCartForm);

A: You can achieve this via param return_url. On click of "Add to cart", fire your ajax call with return_url set as current product page URL. When clicking on "Buy Now", set the param to cart page URL. Magento will handle the rest. You'll need to have some JS in place for both of the buttons.
Edit :
Below is the code I could gather. In addtocart.phtml file, your buttons will go like this :
<button type="button" title="<?php echo $buttonTitle ?>" id="product-addtocart-button" data-url="<?php echo Mage::helper('core/url')->getCurrentUrl(); ?>" class="button btn-cart" onclick="productAddToCartForm.submit(this)"><?php echo $buttonTitle ?></button>
<button type="button" title="<?php echo $buttonTitle ?>" id="product-buynow-button" data-url="<?php echo $this->getUrl('checkout/cart'); ?>" class="button btn-cart" onclick="productAddToCartForm.submit(this)"><?php echo $this->__('Buy Now'); ?></button>

Now, in the form in view.phtml file, add a hidden field like this :
<input type="hidden" name="return_url" id="return_url" value="" />

In that file, you can see the JS in action to submit the form. Only a single line modification needed now here. Final JS will be like :
productAddToCartForm.submit = function(button, url) {
    if (this.validator.validate()) {
        jQuery('#return_url').val(jQuery(button).attr('data-url'));
        var form = this.form;
        var oldUrl = form.action;

        if (url) {
            form.action = url;
        }
        var e = null;
        try {
            this.form.submit();
        } catch (e) {
        }
        this.form.action = oldUrl;
        if (e) {
            throw e;
        }

        if (button && button != 'undefined') {
            button.disabled = true;
        }
    }
}.bind(productAddToCartForm);

Here, I have just set the input field value before sending the data to controller.

A: As Prateek suggests, you can use the redirect_url parameter to force redirection after the product has been added to cart.
Refer to Mage_Checkout_CartController::addAction() to see what happens when you add your product to cart and in particular to Mage_Checkout_CartController::_goBack() to see how redirection works.


text:
Q: How to integrate 2 compoonent spline function I have a Spline function defined as follows.
Points = {{0, 0}, {0, 1}, {1, 1}, {1, 0}, {0, 0}};

bsf = BSplineFunction[Points, SplineDegree -> 1];

A Parametric Plot look like this:
ParametricPlot[bsf[r], {r, 0, 1}]

But when I try to do NIntegrate, I get for the first component
NIntegrate[bsf[t][[1]], {t, 0, 1}]

An output of 0.5 as it should be, but for the second component
NIntegrate[bsf[t][[2]], {t, 0, 1}]

I get as an output

I still get the correct output though. But If I just type
NIntegrate[bsf[t], {t, 0, 1}]

I just get error

Why is this and how can I fix this?
Thanks in advance!

A: Indexed.
NIntegrate[Indexed[bsf[t], 1], {t, 0, 1}]
NIntegrate[Indexed[bsf[t], 2], {t, 0, 1}]

0.5.

0.5.

A: There are two options I could come up with here.  The first is to define your bsf function to only accept numerical inputs. That is,
Points = {{0, 0}, {0, 1}, {1, 1}, {1, 0}, {0, 0}};
bsf = BSplineFunction[Points, SplineDegree -> 1];
bsfNum[t_?NumericQ, index_] := bsf[t][[index]]

Then,
NIntegrate[gg[t, 1], {t, 0, 1}]
NIntegrate[gg[t, 2], {t, 0, 1}]
(* 0.5 *)
(* 0.5 *)

The issue is that bsf[t] doesn't evaluate to a list of two elements until after you have entered a numerical value for t, and this forces Mathematica to define a numerical function instead.
Alternatively, we can construct the B-spline functions from the BSplineBasis functions, using the knots generated internally by BSplineFunction.  We define,
bsfKnot[t_] = Sum[
   Points[[j + 1]] BSplineBasis[{1, Rationalize@First@bsf["Knots"]}, j, t],
   {j, 0, Length@Points - 1}
  ];

Then, this seems to be the right function:
ParametricPlot[bsfKnot[t], {t, 0, 1}]

In addition, we can use Integrate or NIntegrate:
Integrate[bsfKnot[t][[2]], {t, 0, 1}]
NIntegrate[bsfKnot[t][[2]], {t, 0, 1}]
(* 1/2 *)
(* 0.5 *)


text:
Q: Objective c and events
Possible Duplicate:
Multiple Delegates in Objective C

C# programmer here.
I have a subclass and I want it to fire an event that multiple classes can subscribe to.
I had been using delegates to do this type of thing, but the problem I have is that only one class can subscribe to the delegate.
What is the pattern is objective c to have multiple observers?

A: Use the NSNotificationCenter to register and listen to events:
NSNotificationCenter Class Reference:
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html
Notification Programming Topics:
http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Notifications/Introduction/introNotifications.html%23//apple_ref/doc/uid/10000043i
[ [ NSNotificationCenter defaultCenter ]
    postNotificationName: @"notificationName"
    object:               someObject
]

And then, to listen:
[ [ NSNotificationCenter defaultCenter ]
    addObserver: self
    selector:    @selector( someMethod: )
    name:        @"notificationName"
    object:      theObject
]


text:
Q: Erro: não é possível localizar nem carregar a classe principal Estou em busca da solução do seguinte problema, faço um "OláMundo" no Netbeans e ele está compilando, faço ou outro no Bloco de Notas e no Notepad++, consigo criar a class com o javac Oi.java, mas quando coloco java Oi, aparece o seguinte erro:

"Erro: não é possível localizar nem carregar a classe principal Oi"

OBS: Todos os fóruns que busco fala sobre a configuração da JAVA_HOME, da PATH e da CLASSPATH, todas já foram acertadas, quando coloco para mostrar no Prompt a versão ela aparece normalmente...
Como posso solucionar isso, como consigo rodar no Prompt?
Segue prints abaixo da pasta, do bloco de notas, do prompt e do teste rodando normalmente no Netbeans:

A: Provavelmente você está tentando rodar a classe sem compilar. É preciso compilar o arquivo .java antes:
javac Oi.java

para depois executar:
java Oi

Veja, a classe está funcionando normalmente:

Obs.: Certifique-se de que a classe tenha o mesmo nome do arquivo, se a classe se chama MinhaClasse, o arquivo também deve se chamar MinhaClasse.java.

No print, seu arquivo se chama Oi.java, mas a assinatura da classe esta com nome diferente(public class Oie)

Obs2.: Se tiver informação de package na classe, o compilador vai procurar por essas pastas, e como não vai encontrar vai dar esse erro. Remova a informaçao de package a nao ser que possua hierarquia de pastas do package.

Tente também com o comando abaixo, onde a jvm vai forçar o classpath como a pasta atual e procurar a classe apenas dentro dela:
java -cp . Oi

Nesta resposta e nesta outra do SOEn tem explicações mais detalhadas sobre os motivos que podem ocasionar esse problema.


text:
Q: Copying feed items from opportunity to related account I am trying to copy feeds from an opportunity to it's related account and I it doesn't seems to be so easy. :)
feed is a complex object as can be seen here so basically I want to copy also the comments and likes.

I have searched all over the network for an answer but I haven't seen something similar. For example, I have gone through those links and many more which helped me to understand a little bit more with what I am facing with,

*

*https://www.salesforce.com/developer/docs/api/Content/sforce_api_erd_chatter.htm

*https://developer.salesforce.com/page/Chatter_Code_Recipes
There is 2 types of feeds which I want to be able to copy: TrackedChange and TextPost.
Regarding TrackedChange , I saw that only the system can generate this kind of feed (mentioned in Chatter_Code_Recipes), is there any way I can mimic and post a similar feed on the account?
Regarding TextPost , I have tried to do the following but I have managed only to copy the main feed without its related objects (comment and likes).
FeedItem opf = [SELECT Id, Type,
CreatedById, CreatedBy.FirstName, CreatedBy.LastName,
ParentId, Parent.Name,
Body, Title,
(SELECT Id, FeedItemId,FieldName, OldValue, NewValue
        FROM FeedTrackedChanges),
(SELECT Id, ParentId, CommentBody, CreatedDate,
        CreatedById, CreatedBy.FirstName, CreatedBy.LastName
        FROM FeedComments),
(SELECT CreatedBy.FirstName, CreatedBy.LastName
        FROM FeedLikes)
        FROM FeedItem
WHERE ParentId = '**OPPORTUNITY_ID**' AND ID = '**FEED ID**'];
// system.debug(opf);
// opf.parentId = '**ACCOUNT_ID**';  Doesn't work.. parentId field is
// not writable
FeedItem opfc = opf.clone(false,true);
opfc.parentId = '**ACCOUNT_ID**'; // Changing the parent Id to account Id
insert opfc; // Insert works but I don't see all the related child objects  (comments, likes, etc.)

Some advises please?
Thanks ahead.


text:
Q: Access to fetch at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource I have this api (method get) that is connected to a lambda function that does a simple select from a database, if i test the endpoint with postman with a null body it does work (if i understood, postman is not under the same CORS policy), as well as typing the endpoint on the browser.

But when i try to do a fetch from a simple js, i get the error :
Access to fetch at '...' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I enabled CORS in API Gateway, both with the Enable CORS option

and with the Enable API Gateway CORS when creating a new resource
If i test my endpoint with gateway, i also get that Allow-content-allow-origin : * is in my response header :

What should i do to fix this problem?
here is the JS fetch :
    console.log("pre fetch");

Show();
console.log("post fetch");
function Show(){
fetch("...").then(onResponse);//.then(onJson);
}
function onResponse(response){
    console.log(response);
    return response.json();
}

I removed the onJson to avoid confusion, but even with that in its the same problem.

A: Try to include that in your function too, like this,
I hope this would work:
const headers = {'Content-Type':'application/json',
                    'Access-Control-Allow-Origin':'*',
                    'Access-Control-Allow-Methods':'POST,PATCH,OPTIONS'}
const response = {
    statusCode: 200,
    headers:headers,
    body: JSON.stringify(X),
};
return response;

Here X is the response that you want to return.

A: If you are using Node.js you needs to install cors.
npm install cors.
After installing cors, include it in the page where you are using fetch function as shown below;
const cors = require('cors');
app.use(cors());
and the error will be solved.

A: I made a video on how to fix this.
You need to go into the Lambda function and add special code:
original (does NOT work):
exports.handler = async (event) => {
    // TODO implement
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

new one, that works:
exports.handler = async (event) => {
    // TODO implement
    const response = {
        statusCode: 200,
                headers: {
            "Access-Control-Allow-Headers" : "Content-Type",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "OPTIONS,POST,GET"
        },
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

You can find this solution in here: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html
Only you need to replace the:
  "Access-Control-Allow-Origin": "https://www.example.com",

with
            "Access-Control-Allow-Origin": "*",

Special thanks to user, KnowledgeGainer
ALSO, you need to enable CORS on Gateway API side, just follow instruction from here: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors-console.html


text:
Q: How to use your own solving method in GEKKO? I want to use my own Genetic Algorithm (GA) to solve a Mixed Integer problem:
https://mintoc.de/index.php/Batch_reactor
Can I incorporate my solving method in GEKKO?
something like...
m = GEKKO()
.
.
.

m.options.SOLVER = 'my_GA'

A: GEKKO currently only supports gradient-based built-in solvers. If you are set on using a Genetic Algorithm (Chapter 6 for GA overview), you could run function evaluations with GEKKO to returns an objective value at different trial conditions. You would need to put an m.solve() command inside a loop every new generation of the GA. In GEKKO, you would also need to use m.options.TIME_SHIFT=0 to not update the initial conditions. This would allow repeated evaluations as you change your design variables (e.g. T(t) from MintOC) to find the best objective function value (e.g. x2(tf) from MintOC).
m = GEKKO()

# define model
x2 = m.Var()
T = m.Param()
.
.
.
m.options.TIME_SHIFT=0
m.options.IMODE = 4 # or 7
# GA loop
for i in range(generations):
    T.value = [values from GA]
    m.solve()
    obj = x2.value[-1] # objective

    # additional GA steps to decide new T values

Here is some additional information from the documentation: SOLVER selects the solver to use in an attempt to find a solution. There are free solvers: 1: APOPT, 2: BPOPT, 3: IPOPT distributed with the public version of the software. There are additional solvers that are not included with the public version and require a commercial license. IPOPT is generally the best for problems with large numbers of degrees of freedom or when starting without a good initial guess. BPOPT has been found to be the best for systems biology applications. APOPT is generally the best when warm-starting from a prior solution or when the number of degrees of freedom (Number of Variables - Number of Equations) is less than 2000. APOPT is also the only solver that handles Mixed Integer problems. Use option 0 to compare all available solvers.


text:
Q: Taking a form response, making an api call then displaying the api call in Django I'm trying to have a Django form capture data from a user's input, take the input to make an API call to Aylien API and display the raw json result on the same page.
I'm able to take the form input and successfully make an API call & get the JSON to print on the console, but am having a hard time displaying the call's result on the page.
I keep getting UnboundLocalError: local variable 'api_response' referenced before assignment error. Code below
models.py
from django.db import models

# Create your models here.
class News(models.Model):
    title = models.TextField(max_length=120)

form.py
from django import forms
from .models import News

class NewsForm(forms.ModelForm):
    class Meta:
        model = News
        fields = [
            'title']

views.py
from django.shortcuts import render
from .models import News
from .form import NewsForm
import requests
import aylien_news_api
from aylien_news_api.rest import ApiException

def news_create_view(request):
    ## link form to model for gathering search term from user
    form = NewsForm(request.POST)

    if form.is_valid():
        # create an instance of the aylien api class
        api_instance = aylien_news_api.DefaultApi()

        ## build opts for api call from the response from the user
        opts = {
            'title': form.cleaned_data['title'],
            'language': ['en'],
            'not_language': ['es', 'it'],
            'published_at_start': 'NOW-7DAYS',
            'published_at_end': 'NOW'
        }
        try:
            # List the stories
            api_response = api_instance.list_stories(**opts)
        except ApiException as e:
            print("Exception when calling DefaultApi->list_stories: %s\n" % e)

        ## re-instantiate the form and save to admin
        form.save()
        form = NewsForm()

    else:
        form = NewsForm()

    ## context for models
    context = {
        'form': form,
        'api_response': api_response
    }

    ## render pages in Django dynamically (static HTML is slow to load)
    return render(request, "news/show_result.html", context)

show_result.html

    <form method="GET"> {% csrf_token %}

        {{ form.as_p }}
        <input type="submit", value="Search" />

    </form>

    {{ api_response }}

I'm obviously doing something wrong here, just can't seem to figure out what

A: You are getting this error because your form is invalidated, and api_response will only be defined if the form is valid.
To fix your problem, Change this:
form = NewsForm(request.POST)

To this:
form = NewsForm(request.POST or None)

If you make a GET to your view, your form will be invalid if you pass an empty request.POST, so you need to pass None instead.
Lastly, I'd recommend adding api_response = None in your else clause.  This will prevent api_response from ever being undefined, and your server won't give a 500 error if someone is tampering with the form.


text:
Q: WPF checkbox all not not updating on one checkbox row is unchecked I had a checkbox all column inside the datagrid in WPF C#.
                     <DataGridCheckBoxColumn Binding="{Binding IsSelected,UpdateSourceTrigger=PropertyChanged}" CanUserSort="False">
                    <DataGridCheckBoxColumn.ElementStyle>
                        <Style TargetType="CheckBox" BasedOn="{StaticResource {x:Type CheckBox}}">
                            <Setter Property="VerticalAlignment" Value="Center"/>
                            <Setter Property="HorizontalAlignment" Value="Center"/>
                        </Style>
                    </DataGridCheckBoxColumn.ElementStyle>
                    <DataGridCheckBoxColumn.HeaderTemplate>
                        <DataTemplate x:Name="dtAllChkBx">
                            <CheckBox Name="cbxAll" HorizontalAlignment="Center" Margin="0,0,5,0" IsEnabled="{Binding Path=DataContext.IsCbxAllEnabled,RelativeSource={RelativeSource AncestorType=DataGrid}}"
                                      IsChecked="{Binding Path=DataContext.AllSelected,RelativeSource={RelativeSource AncestorType=DataGrid},UpdateSourceTrigger=PropertyChanged}"/>
                        </DataTemplate>
                    </DataGridCheckBoxColumn.HeaderTemplate>
                </DataGridCheckBoxColumn>

When I check the All checkbox, of course, it will mark all the checkboxes, but once I uncheck one checkbox, the All checkbox is still checked. This should be unchecked. How should I do that using WPF C#.

A: If I understood you correctly - after any change of IsSelected property inside collection item you should update AllSelected value.
So, you need some callback inside all your items(event or Action or any mechanism you want) and change get logic for AllSelected
Here is some draft for item IsSelected property and constructor:
public bool IsSelected {
    get { return isSelected; }
    set {
        isSelected = value;
        OnPropertyChanged();
        if (globalUpdate != null) globalUpdate();
    }
}

public ItemClass(Action globalUpdate, ...your parameters) {
    this.globalUpdate = globalUpdate;
    ...do smth with your parameters
}

Example of usage:
new ItemClass(() => OnPropertyChanged("AllSelected"))

And of course don't forget about AllSelected getter
public bool AllSelected {
        get { return YourGridItemsCollection.All(item => item.IsSelected); }

Now when you check manually all items then AllSelected will be automatically checked, and unchecked when you uncheck any item.


text:
Q: Complexity in implementing Predictive Intelligence? We are a relatively new SFMC partner in Asia. We are told that Predictive Intelligence implementation is very tricky that it has to be done by SFMC Internal Service team. Is it true? Where is the best resource to get tutorial on the steps to implement PI? Many thanks in advance.

A: Perhaps one of the SFMC folks could chime in, but as far as I know, it's an integration behind the scenes... so there's no front-end for doing the provisioning.  Plus, there's quite a bit of data discovery required to build the product, category, etc., schemas.
Same thing goes for Audience Builder, but I've heard they're working on a front-end for provisioning.


text:
Q: Oculus Quest: how to detect recording / screenshot Is there a way - either through the oculus SDK or the Android SDK, to detect when the user is recording, streaming or taking a screenshot via the built in features of the Oculus Quest 2?
If so, how can this be queried or a callback be set?


text:
Q: Show results of employees whose age is equal to 65 Show results of employees whose age is equal to 65.
I want to get results whose age is 65 , i.e if any employee age comes to 65 years on 24-02-2022 his results I want to show, after 25-02-2022 his results should not display for the total 12 months, want to show for only one day.
Any help
SELECT id,
      first_name,
      last_name,
      floor(datediff(CURDATE(),date_of_birth)/365) as age,
      date_of_birth
from employee
where floor(datediff(CURDATE(),date_of_birth)/365)=65;

Sample data
employee name - James

date of birth - 1957-02-24

age - 65

At this date he is 65 years and should not display after this date, i.e from 25-02-2022 to 24-02-2023

A: SELECT id,
       first_name,
       last_name,
       TIMESTAMPDIFF(YEAR, date_of_birth, CURRENT_DATE) AS age,
       date_of_birth
FROM employee
HAVING age = 65;

TIMESTAMPDIFF() returns the amount of complete (not rounded) units between two dates.

I want only exactly at the starting date when he is 65 years and 0 days.

SELECT id,
       first_name,
       last_name,
    -- TIMESTAMPDIFF(YEAR, date_of_birth, CURRENT_DATE) AS age,
       65 AS age,
       date_of_birth
FROM employee
WHERE date_of_birth = CURRENT_DATE - INTERVAL 65 YEAR;

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=1a63622ffffef8167bc1be074a3a119b


text:
Q: Scala, how to specify function parameter with multiple traits? I have following piece of code, and I think my question will be apparent once you see it.
trait hasId {
  def id: String
}

trait hasCount {
  def count: Int
}

case class Foo(id: String, count: Int) extends hasId with hasCount

// This is the function I want to write
def printData(data: hasId and hasCount): Unit = {
  println(data.id + ": " data.count);
}

How should I do to declare the function signature?

A: The solution to the answer is with keyword, which is used in the meaning of your and. Generics as Terry Dactyl wrote are one possible solution:
def printData[T <: hasId with hasCount](data: T): Unit = {
  println(data.id + ": " + data.count)
}

Another is a type alias using with:
type hasIdAndCount = hasId with hasCount
def printData(data: hasIdAndCount): Unit = {
  println(data.id + ": " + data.count)
}

Or even directly:
def printData(data: hasId with hasCount): Unit = {
  println(data.id + ": " + data.count)
}

A: def hasData[T <: HasId with HasCount](data: T): Unit = ???

A: I somehow like @TerryDactyl's answer better, but here is another way:
// This is the corrected function
def printData(data: hasId with hasCount): Unit = {
 println(data.id + ": " + data.count)
}

EDIT:
Since the comments showed that I needed to explain and since the scastie link didn't work, following is the compiled code, with the compilation errors, I hope it helps:
scala> :paste
// Entering paste mode (ctrl-D to finish)

trait hasId {
  def id: String
}

trait hasCount {
  def count: Int
}

trait Both extends hasId with hasCount

case class Foo(id: String, count: Int) extends Both
case class Bar(id: String, count: Int) extends hasId with hasCount
case class Baz(id: String, count: Int) extends Both

def printData(data: hasId with hasCount): Unit = {
 println(data.id + ": " + data.count)
}

def printDataT[T <: hasId with hasCount](data: T): Unit = {
 println(data.id + ": " + data.count)
}

val s = Seq(Foo("idFoo", 1), Bar("idBar", 2))

val fooss = Seq(Foo("idFoo", 1), Foo("idFoo2", 2))
val boths = Seq(Foo("idFoo", 1), Baz("idBaz2", 2))

s.foreach(printData)
fooss.foreach(printData)
boths.foreach(printData)

fooss.foreach(printDataT[Foo])
fooss.foreach(printDataT[Both])
boths.foreach(printDataT[Both])
boths.foreach(printDataT[Foo])

s.foreach(printDataT[hasId with hasCount])
s.foreach(printDataT[Both])
s.foreach(printDataT[Foo])

// Exiting paste mode, now interpreting.

<console>:54: error: type mismatch;
 found   : Foo => Unit
 required: Product with Serializable with hasId with hasCount => ?
              s.foreach(printDataT[Foo])
                                  ^
<console>:48: error: type mismatch;
 found   : Foo => Unit
 required: Both with Product with Serializable => ?
              boths.foreach(printDataT[Foo])
                                      ^
<console>:51: error: type mismatch;
 found   : Both => Unit
 required: Product with Serializable with hasId with hasCount => ?
              s.foreach(printDataT[Both])
                                  ^


text:
Q: Excel hide row if there's a value in cell I am look to have a entire row hidden if a value is entered into a certain column of that row "M".
Example I have a list of items and column M is PO number, when the PO number is entered for that line item I would like the row to disappear(hidden).
Goal is to only have items without a PO number to be in the list.

A: Right-click on column "m" and then click Hide.


text:
Q: Secure Web-Client and API in Spring-Security Configuration in one Application I have setup a Spring boot application running in tomcat to be distributed as WAR to server
I have several HTML pages that does work with form security but I am trying to add a API also therefore I am switching to JWT.
My effort is then to combine local client with back end API in one WAR file as I happen to know it is possible with Spring Security
EDIT: My gradle
plugins {
    id 'org.springframework.boot' version '2.2.1.RELEASE'
    id 'io.spring.dependency-management' version '1.0.8.RELEASE'
    id 'java'
    id 'war'
}
....
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'com.auth0:java-jwt:3.8.3'

in my SecurityConfiguration.java I have
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // remove csrf and state in session because in jwt we do not need them
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                // add jwt filters (1. authentication, 2. authorization)
                .addFilter(new JwtAuthenticationFilter(authenticationManager()))
                .addFilter(new JwtAuthorizationFilter(authenticationManager(), this.userRepository))
                .authorizeRequests()
                // configure access rules
                .antMatchers("/index.html").permitAll()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers(HttpMethod.POST, "/login").permitAll()
                .antMatchers("/api/public/management/*").hasRole("MANAGER")
                .antMatchers("/api/public/admin/*").hasRole("ADMIN")
                .anyRequest().authenticated();
    }

EDIT: Added the JwtAuthenticationFilter
public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    private AuthenticationManager authenticationManager;

    JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    /* Trigger when we issue POST request to /login
    We also need to pass in {"username":"admin", "password":"password"} in the request body
     */
    @Override
    public Authentication attemptAuthentication(
            HttpServletRequest request,
            HttpServletResponse response
    ) throws AuthenticationException {

        // Grab credentials and map them to LoginViewModel
        LoginViewModel credentials = null;
        try {
            credentials = new ObjectMapper().readValue(request.getInputStream(), LoginViewModel.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // Create login token
        assert credentials != null;
        System.out.println("Credentials : " + credentials.getUsername() + ":" + credentials.getPassword());
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                credentials.getUsername(),
                credentials.getPassword(),
                new ArrayList<>()
        );

        // Authenticate user

        return authenticationManager.authenticate(authenticationToken);
    }

    @Override
    protected void successfulAuthentication(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain chain,
            Authentication authResult
    ) {
        // Grab principal
        UserPrincipal principal = (UserPrincipal) authResult.getPrincipal();

        // Create JWT Token
        String token = JWT.create()
                .withSubject(principal.getUsername())
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .sign(HMAC512(SECRET.getBytes()));
        System.out.println("Token : " + TOKEN_PREFIX + token);
        // Add token in response
        response.addHeader(HEADER_STRING, TOKEN_PREFIX + token);
    }
}

EDIT: Added JwtAuthorizationFilter
public class JwtAuthorizationFilter extends BasicAuthenticationFilter {
    private UserRepository userRepository;

    JwtAuthorizationFilter(AuthenticationManager authenticationManager, UserRepository userRepository) {
        super(authenticationManager);
        this.userRepository = userRepository;
    }

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain chain
    ) throws IOException, ServletException {
        // Read the Authorization header, where the JWT token should be
        String header = request.getHeader(HEADER_STRING);

        // If header does not contain BEARER or is null delegate to Spring impl and exit
        if (header == null || !header.startsWith(TOKEN_PREFIX)) {
            chain.doFilter(request, response);
            return;
        }

        // If header is present, try grab user principal from database and perform authorization
        Authentication authentication = getUsernamePasswordAuthentication(request);
        SecurityContextHolder.getContext().setAuthentication(authentication);

        // Continue filter execution
        chain.doFilter(request, response);
    }

    private Authentication getUsernamePasswordAuthentication(HttpServletRequest request) {
        String token = request.getHeader(HEADER_STRING)
                .replace(TOKEN_PREFIX, "");

        // parse the token and validate it
        String userName = JWT.require(HMAC512(SECRET.getBytes()))
                .build()
                .verify(token)
                .getSubject();

        // Search in the DB if we find the user by token subject (username)
        // If so, then grab user details and create spring auth token using username, pass, authorities/roles
        if (userName != null) {
            System.out.println("userName :" + userName);
            User user = userRepository.findByUsername(userName);
            UserPrincipal principal = new UserPrincipal(user);
            return new UsernamePasswordAuthenticationToken(userName, null, principal.getAuthorities());
        }
        return null;
    }

Normally I could just execute the index.html from the browser by running https://localhost:8443/index
It does give me an error

There was an unexpected error (type=Forbidden, status=403). Access
  Denied

HOWEVER if i test it in Postman WITH a Bearer token It serves the page
My question is how to exclude the HTML content from the JwtAuthenticationFilter and how to actually do I authorize my HTML content?
My thoughts is to combine formLogin() with JWT but I cannot find sample code to teach me.
Please ask any other code part if you need

A: It's hard to say exactly what's going on with so much custom code, but here are some tips based on your explanation.
Possibility #1
First, your JwtAuthenticationFilter or your JwtAuthorizationFilter may be expecting too much. Do they try and authentication and authorize the request when there is no bearer token in the request?
A good way to simplify this is to upgrade to Spring Security 5.1+ and use its bearer token support:
http
    .authorizeRequests()
        .antMatchers("/index.html").permitAll()
        ... // other matchers
        .anyRequest().authenticated()
        .and()
    .oauth2ResourceServer()
        .jwt();

It only activates when there is a bearer token present. Also, it disables CSRF for you for requests that contain a bearer token.
You can add formLogin(), but it is a bit at odds with sessionCreationPolicy(STATELESS). Form login needs a sessioned web application. If you want a username/password client that sends its credentials on every request, then you need httpBasic() instead, which you can do like so:
http
    .authorizeRequests()
        .antMatchers("/index.html").permitAll()
        ... // other matchers
        .anyRequest().authenticated()
        .and()
    .httpBasic()
        .and()
    .oauth2ResourceServer()
        .jwt();

With this setup, httpBasic will engage only when using Authorization: Basic and oauth2ResourceServer will engage only when using Authorization: Bearer.
If you really are wanting formLogin (a UI where a user can fill out an HTML form), then you don't want the application to be stateless. You can do:
http
    .authorizeRequests()
        .antMatchers("/index.html").permitAll()
        ... // other matchers
        .anyRequest().authenticated()
        .and()
    .formLogin()
        .and()
    .oauth2ResourceServer()
        .jwt();

Possibility #2
Or, second, you might say that the URIs for your API are completely separate from your client application.
For example, URIs for your client app all start with /app.
And URIs for your API all start with /api.
If that's the case, then you can create two instances of WebSecurityConfigurerAdapter:
@Configuration
@Order(100)
public class AppConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) {
        http
            .requestMatchers()
                .antMatchers("/app/**")
                .and()
            .authorizeRequests()
                .antMatchers("/app/index.html").permitAll()
                .anyRequest().authenticated()
                .and()
             .formLogin();
    }
}

@Configuration
@Order(101)
public class ApiConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) {
        http
            .requestMatchers()
                .antMatchers("/api/**")
                .and()
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .sessionManagement().sessionCreationPolicy(STATELESS)
                .and()
            .addFilter(new JwtAuthenticationFilter(...))
            .addFilter(new JwtAuthorizationFilter(...))
            .csrf().disable();
    }
}

Note that both of these setups acknowledge that you don't want to disable CSRF for your entire application. You want that protection on for the client app.

A: After investigating I found the answer
Thank you @jzheaux for your Input it was instrumental in clarifying what I need to do.
I needed to split the API from the WebClient and have JWT on the Api part but FormLogin on the WebClient part.
It is is probably possible to to combine the two but my experience with coding is not there yet


text:
Q: How do I establish path from VS code to cl.exe compiler? I have MSVC compiler installed on my pc and it works fine in dev command prompt. However, I am unable to establish path from VS code to cl.exe compiler.
Is there some problem with my args?
        "args": [
            "/Zi",
            "/std:c++latest",
            "/EHsc",
            "/Fe:",
            "${fileDirname}\\rooster.exe",
            "${workspaceFolder}\\*.cpp"
        (BTW, I am a complete beginner and this setup is necessary for a tutorial I am taking)


text:
Q: Is the Young's Modulus different for Compressive and Tensile Stress? My textbook says that the magnitude of strain produced is the same whether the stress is tensile or compressive. So the Young's modulus, which is the ratio of (tensile or compressive) stress to the longitudinal strain, should be the same for both compressive and tensile stress.
However, my textbook gives the Young's Modulus Of Bone for Tensile stress as 16 x 10^9 N/m^2 and for Compressive Stress as 9 x 10^9 N/m^2.
Since the Young's Moduli for other substances have been given only one value for both tensile and compressive stress, I was wondering if Bone is a special case, and if so, why?

A: Well-defined, solid continuum materials generally have the same compressive and tensile Young's moduli.
The reason is that the elastic moduli measure slight displacements from an energy minimum, typically representing the equilibrium spacing of atoms balanced between attraction and repulsion. All smooth energy minima look like symmetric parabolas close up. Thus, the restoring forces from symmetric slight compression and tension are nearly identical, and so are the corresponding Young's moduli.
What about bone? Bone is a biological material with a variety of compositions and some degree of porosity. The description "bone" is too ambiguous: What bone, from what animal? Was the same material used for both the compressive and tensile tests? How did the researchers correct for the discrepancy between the measured cross-sectional area and the actual material area, given the porosity? And in particular, did the compressive displacement involve slight atomic shifting only, or did some of the struts forming the porous cells buckle, an effect that wouldn't occur in tension? (Differences in compressive and tensile behavior in such porous materials is discussed in Gibson's & Ashby's Cellular Materials.)
For these reasons, I'd expect nearly identical compressive and tensile Young's moduli in most engineering materials (solid ceramics, metals, polymers below the glass transition temperature) but am not very surprised to see different experimental results for an entry labeled simply "bone." I would agree with you (in contrast to the other answer, which I think deeply confuses stiffness and strength) that bone is a special case in this context.

A: Ceramics usually are like that, large difference between compression and tension. Same for nanotubes, fiber based materials in general, bulk glass. Bone is like that too.
Few materials are the same in compression and tension. Metals, some crystals. but those are more stable and easy to measure. So we have more information about them. Probably this is why measuring just one property became popular.
But I would say materials with different compression and tension characteristics are more common in practice.


text:
Q: Reference rewriten address with Request.Url I am using a custom asp.net rewriting module for some time now, and I would like to know how to reference/get a rewritten address (the url that shows in address bar) of an original url using Request.Url?
When I reference url with Request.Url.AbsoluteUri I always get the original address and not the rewritten one. One solution is to encode the original url once again, but I was looking for a different solution where I could actually reference this new url.
Thanks

A: I was looking for Request.RawUrl.


text:
Q: Extending a morphism $\mathbb{A}^1-0\to \mathbb{P}^1$ to $\mathbb{A}^1$ I'm doing some exercise in which I need to prove that every morphism of prevarieties (As in Gathmann's, in fact it's an exercise from Gathmann's notes) $\mathbb{A}^1-0\to \mathbb{P}^1$ can be extended to a morphism $\mathbb{A}^1\to \mathbb{P}^1$.
My attempt started by taking the open cover
$$U_0=\{[x:y]\mid x\neq 0\},U_1=\{[x:y]\mid y\neq 0\}\subseteq \mathbb{P}^1.$$
Then, from what I have done, it seems that a morphism $f:\mathbb{A}^1-0\to \mathbb{P}^1$ is just a map such that $f|_{f^{-1}(U_i)}:f^{-1}(U_i)\to U_i$ is a morphism of affine varieties, thus, after replacing $U_0,U_1\cong \mathbb{A}^1$ by a very simple map and $\mathbb{A}^1-0$ by $V(xy-1)\subseteq \mathbb{A}^2$ the induced maps must be polynomials.
I think up to the part in italic, I'm in the right track (but I think it's just the beginning). I'm not sure the part in italic can really help.
Now what I think follows is, consider the morphism $f:\mathbb{A}^1-0\to \mathbb{P}^1$. Then we consider the two restrictions $f_0:V_0\to U_0$, $f_1:V_1\to U_1$. I want to use this information to find some place to send $0$, but I'm not sure how I should do that.
I found a question about a map $\mathbb{A}^2-0\to \mathbb{P}^1$ which cannot be extended, and I see what fails there, but I'm not sure if I can use that as an idea to find the value of $f(0)$. It'd be more like that if I find the appropiate value for $f(0)$ then that might help me prove continuity. In a comment a suggestion for my exercise is given but I'm not sure it fits the way I'm trying to do it.
So, is there any idea about how can I continue with my attempt? If not, is there any idea about how can the attempt in that comment continue? Or an idea about a better approach for it?

For (a), I think the idea should be (I'm being very loose, but this works in general) to factor. In the sense that if $t$ is a coordinate on $\mathbb{A}^1$ then near $0$ your map looks something like $t↦[t^2+t,t^3−t^2]$. As it stands this formula does not determine a map at $0$. But away from $0$ it's the same as $[t+1,t^2−t]$, and that formula does say something at $0$.


text:
Q: 'open link in new tab' option missing when right clicking a link on website when i use  it works and option for new tab can be seen in context menu on right clicking the link . but if i use JavaScript/jQuery its not showing? i used window.location,window.open etc but it doesn't show. now i am using onclick attribut on div,but still not showing. does it only shows when using anchor?
div class='miniShell'>
      <div class='mini' onclick="openLink('<?php echo $UrlA?>')">
<?php echo ucwords($TitleA) ?>

      <div class='mini' onclick="openLink('<?php echo $UrlB?>')">
<?php echo ucwords($TitleB) ?>

      <div class='mini' onclick="openLink('<?php echo $UrlC?>')">
<?php echo ucwords($TitleC) ?>

      <div class='mini' onclick="openLink('<?php echo $UrlD?>')">
<?php echo ucwords($TitleD) ?>

in jquery:
function openLink(link){
                 window.open('http://localhost/mysite/story/'+link,'_self');
             }

Browser:google chrome

A: A div isn't a link. To create a link use the  tag. You could replace the div tag with an a tag that has virtually the same methods to achieve this goal. Although your HTML redirects the page to a certain link, the browser doesn't classify it as a "link".

A: Continue to @Rigidity answer, too a window.open is a function, is not a generic link, it is a javascript method, and the browser will not recognize it as a link and hence the contextmenu of a normal link will not apper in your div


text:
Q: Переключатель между Activity Ввёл следующее в MainActivity.java:
public class MainActivity extends ActionBarActivity implements View.OnClickListener {

Button btnActTwo;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ListView lvMain = (ListView) findViewById(R.id.lvMain);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, names);

    lvMain.setAdapter(adapter);

    btnActTwo = (Button) findViewById(R.id.btnActTwo);
    btnActTwo.setOnClickListener(this);
}

public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btnActTwo:
            Intent intent = new Intent(this, ActivityTwo.class);
            startActivity(intent);
            // TODO Call second activity
            break;
        default:
            break;
    }

}

}

public class MainActivity extends Activity implements ActionBar.TabListener {

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ActionBar bar = getActionBar();

    bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    ActionBar.Tab tab = bar.newTab();
    tab.setText("Tab1");
    tab.setTabListener(this);
    bar.addTab(tab);

    tab = bar.newTab();
    tab.setText("Tab2");
    tab.setTabListener(this);
    bar.addTab(tab);

}

}

При запуске приложения вывод ошибку:
Error:(52, 8) error: duplicate class: startandroid.ru.myschool.MainActivity
Error:Execution failed for task ':app:compileDebugJava'.

Compilation failed; see the compiler error output for details.

Что делаю не так?
A: Знание англосаксонского хотя бы на базовом уровне очень сильно помогает в программировании.
В данном случае компилятор ругается на классы с одинаковым именем в одном пакете. Так нельзя. Переименуйте один из них и подумайте зачем вам вообще их два. Проще переключаться меж разными отображениями в одном классе активити.


text:
Q: Can't perform 'text' command from C# I'm trying to perform full text search with MongoDb 3.
This query works fine for me:
var q = new QueryDocument(BsonSerializer.Deserialize<BsonDocument>(string.Format("{{ $text: {{ $search: {0} }} }}", JsonConvert.ToString(query.Query)));
return await context.Books.Find(q).ToListAsync();

But now I want to sort results by relevancy using textScore field.
I'm trying to use a such code:
public static async Task<IEnumerable<T>> Search<T>(this IMongoDatabase database, string search)     where T : class, new()
        {
            var textSearchCommand = new CommandDocument
            {
                { "text", typeof(T).Name },
                { "search", search }
            };
            var commandResult = await database.RunCommandAsync<TextSearchQueryResult<T>>(    textSearchCommand);

            return commandResult.Ok ? commandResult.Results.OrderBy(t => t.Score).Select(t => t.    Record) : null;
        }

class TextSearchQueryResult<T> : CommandResult
{
    public TextSearchQueryResult(BsonDocument response)
        : base(response)
    {
    }

    public IEnumerable<TextSearchResult<T>> Results
    {
        get
        {
            var results = Response["results"].AsBsonArray.Select(row => row.AsBsonDocument);
            var resultObjects = results.Select(item => item.AsBsonDocument);

            return resultObjects.Select(row => BsonSerializer.Deserialize<TextSearchResult<T>>(row));
        }
    }
}

public class TextSearchResult<T>
{
    public T Record { get; set; }
    public double Score { get; set; }
}

Launching this command I'm getting a such error:
Command text failed: no such command: text

Another approach I found:
return await context.Books
                    .Find(Builders<Book>.Filter.Text(query.Query))
                    //.Project(Builders<Book>.Projection.Include(new StringFieldDefinition<Book>("textScore")))
                    .Sort(Builders<Book>.Sort.MetaTextScore("textScore"))
                    .ToListAsync();

But in this case I'm getting a such error:
Can't canonicalize query: BadValue must have $meta projection for all $meta sort keys (code: 17287)

A: I found one possible approach using aggregation.
var pipeline = new List<BsonDocument>
{
    BsonSerializer.Deserialize<BsonDocument>("{ $match: { $text: { $search: " + JsonConvert.ToString(query.Query) + " } } }"),
    BsonSerializer.Deserialize<BsonDocument>("{ $sort: { score: { $meta: \"textScore\" } } }")
};

var result = await context.Books.AggregateAsync(new BsonDocumentStagePipelineDefinition<Book, Book>(pipeline));
return await result.ToListAsync();

As I can see the result differs from my previous approach. And seems is close to relevant result.