text:
Q: Make dynamic AlertDialog with checkboxes of ArrayList I am trying to build an dynamic dialog window "Which number would you take" in my onNewIntent method for any Integer ArrayList for example [1,9,13] but I dont know how can I get it to work since it is dynamic
onNewIntent method:
@Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub
        super.onNewIntent(intent);

         // getIntent() should always return the most recent
        setIntent(intent);

        //I added here this part to receive the intent from onPostExecute //
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            ArrayList<Integer> routeList = extras
                    .getIntegerArrayList("stop_route");
            for (int item : routeList) {
               // System.out.println("The Intent is not empty: " + item);
                AlertDialog.Builder adb = new AlertDialog.Builder(this);
                checkbox = new CheckBox(this);
                checkbox.setId(item);
                checkbox.setText(item);

            }
        }
    }

A: First of all, note that MaterialDialog extends DialogBase, which extends AlertDialog. While a very small number of the stock methods are purposely deprecated and don't work, you have access to methods such as dismiss(), setTitle(), setIcon(), setCancelable(), etc. Alternatives are discussed below.
Here's a basic example that mimics the dialog you see on Google's Material design guidelines (here: http://www.google.com/design/spec/components/dialogs.html#dialogs-usage). Note that you can always substitute literal strings and string resources for methods that take strings, the same goes for color resources (e.g. titleColor and titleColorRes).
new MaterialDialog.Builder(this)
    .title(R.string.title)
    .content(R.string.content)
    .positiveText(R.string.agree)
    .negativeText(R.string.disagree)
    .show();

On Lollipop (API 21+) or if you use AppCompat, the Material dialog will automatically match the positiveColor (which is used on the positive action button) to the colorAccent attribute of your styles.xml theme.
If the content is long enough, it will become scrollable and a divider will be displayed above the action buttons.
You can refer this github link
https://github.com/afollestad/material-dialogs


text:
Q: Why does my linked list code result in link errors? I'm new to linklist, and i'm having a tough time with it. I'm trying to display some values that i've appended to the nodes, But i keep getting linkerror messages. Here is what I have so far.
LinkList.h
-

    #ifndef LINKLIST_H
    #define LINKLIST_H

    class LinkList
    {
    private:
        struct ListNode
        {
            int value;
            ListNode *next;
        };

        ListNode *head;

    public:
        LinkList();
        void insertNode(int);

        void deleteNode(int);
        void appendNode(int);
        void display() const;

        //~LinkList();
    };
    #endif

Impl.cpp
-

    #include <iostream>
    #include "LinkList.h"
    using namespace std;

    void LinkList::appendNode(int num)
    {
        ListNode * newNode;
        ListNode * nodePtr;

        newNode = new ListNode;
        newNode->value = num;
        newNode->next = NULL;

        if(!head)
        {
            head = newNode;
            head->value = num;
            head->next=NULL;
        }
        else
        {
            nodePtr = head;

            while(nodePtr->next!=NULL)
                nodePtr = nodePtr->next;
            newNode = new ListNode;
            newNode->value = num;
            newNode->next = NULL;

            nodePtr->next = newNode;
        }
    }

    void LinkList::display() const
    {
        ListNode *nodePtr;
        nodePtr = head;

        while (nodePtr != NULL)
        {
            cout << nodePtr->value << endl;

            nodePtr = nodePtr->next;
        }
    }

LinkList::LinkList()
{
    head = NULL;
}
main.cpp
-

    #include <iostream>
    #include "LinkList.h"

    using namespace std;

    int main()
    {
        LinkList mine;

        mine.appendNode(6);
        mine.appendNode(9);
        mine.appendNode(11);

        mine.display();

        return 0;
    }

I fixed some of the initial problems but the program just crashes when it  runs and i'm not sure why
I'm not sure what the problems is, any help would be greatly appreciated.

A: You declared a LinkList constructor, and a destructor, but you did not define them:
LinkList::LinkList() : head(NULL)
{
}

LinkList::~LinkList()
{
    // delete your memory here...
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Confusion on a directional derivative expression I'm studying "A Visual Introduction to Differential Forms and Calculus on Manifolds" and came across a confusing part on intro to directional derivatives. First the definition

The directional derivative of $f:\mathbb{R}^2\to\mathbb{R}$ at $(x_0,y_0)$ in the direction of the unit vector $u=[a,b]^T$ is
  $$D_uf(x_0,y_0)=\lim_{t\to 0}\frac{f(x_0+ta,y_0+tb)-f(x_0,y_0)}{t}$$
  if this limit exists

This definition makes sense. But then there's:

To remind ourselves of some other equivalent notations, notice that if we let $p=(x_0,y_0)$ then we can also write
  $$\lim_{t\to 0}\frac{f(x_0+ta,y_0+tb)-f(x_0,y_0)}{t}=\frac{d}{dt}\bigg(f(p+tu)\bigg)\bigg|_{t=0}$$

I don't understand how the expression on the right came about. The expression on the left indicates the incremental change in $f$ as we vary the vector $x$ from its initial value $[x_0,y_0]^T$, which is why it makes sense. I thought maybe we could write $g(t)=f(x_0+ta,y_0+tb)$, and so its derivative would be
$$\lim_{h\to 0}\frac{f(x_0+ta+ha,y_0+tb+hb)-f(x_0+ta,y_0+tb)}{h}$$
which is the same as the first $D_u$ expression when we put $t=0$. But I'm still not 100% certain since this seems like a very roundabout way of getting the same thing. Why even go through so much trouble if we have a perfectly good definition in the first place? Apologies if this is a naive question.

A: Start on the other side:
$$\frac{d}{dt} \bigg( f(p+tu) \bigg)\bigg|_{t=0} = \lim_{h\to 0} \frac{f(p+(0+h)u)-f(p+(0)u)}{h}. $$
Now change the limit variable to $t$.
Addendum. This reworking of the directional derivative is useful because it makes it clear that it coincides with the standard one-dimensional derivative of the restriction of $f$ to the line defined the point $p$ and the vector $u$. This links them to the usual intuition for partial derivatives (directional derivatives where said line is either horizontal or vertical) and allows us to think of subtleties such as "if all directional derivatives of $f$ exist at a point, does the differential of $f$ necessarily exist?" in a more geometrical sense. (Spoiler: it doesn't)

A: Define a new function of a single variable $t$ as
$$g(t):=f(x_0+at, y_0+bt)$$
You can see $g$ as a composite of $f$ with the single variable function
$$t\longmapsto (x_0+at, y_0+bt)$$
Then by definition of the derivative for functions of a single variable, we have
$$g'(t)=\displaystyle\lim_{h\to 0}\frac{g(t+h)-g(t)}{h}$$
and the derivative at $t=0$ is given by
$$g'(0)=\displaystyle\lim_{h\to 0}\frac{g(h)-g(0)}{h}$$
If we now substitute in for $g(t)$, we get
$$g'(0)=\displaystyle\lim_{h\to 0}\frac{f(x_0+ah, y_0+bh)-f(x_0,y_0)}{h}$$
which is precisely the directional derivative of $f$ at $(x_0,y_0)$, along the direction given by $(a,b)$.


text:
Q: My C "Hello, world!" program isn't compiling I wanted to learn C, so I decided to start a C project and try out the canonical "Hello, world!" program in Visual Studio.
So I put this code in
#import <stdio.h>

main()
{
    printf("Hello, world!");
}

and got three errors:

IntelliSense: cannot open source file "C:/.../stdio.tlh"
  IntelliSense: identifier "printf" is undefined
  IntelliSense: PCH warning: cannot find a suitable header stop location. An intellisense
  PCH file was not generated.

Apparently I'm setting up my project wrong or I don't have the header files I need or something like that.
I'm sure this seems like a really basic problem, but I haven't really used C before so I'm stuck and don't know what to do. What am I doing wrong and how do I fix it?

A: #import should be #include.

A: It's not #import, it's #include.

A: You should use #include instead of #import

A: Couple of points that others have not pointed out:

*

*main() should return int

*Your string literal argument to printf should have a new line.


text:
Q: Retrieving response of POST (with custom header in HTML) request and use it as variable in front-end page I need to write a web-page in which I embed a chart.
The page I wrote is the following:

GO!

If I manually set ChartToken with the correct string this is working. However, the value of ChartToken should be retrieved via a POST request.
I have been told that the POST request should go in the back-end server. However, I don't even know how to write in the back-end server and how to write the POST request. Also, I'm not sure if I really need to write in the back-end or I could simply make the POST request in the front-end page above.
At the moment, in order to obtain the ChartToken I use Advanced REST client. I fill in the Advanced REST client fields the values for the url:
https://url.com/1/embeddedCharts

for the RAW headers:
Authorization: Token YYYYYYYY
Content-Type: application/json

and for the RAW payload:
{"apiToken": "YYYYYYYY",
"chartId": "ZZZZZZZ"}

(notice that the Athorization: Token and the apiToken are the same) and I receive as response:
{
"token": "KKKKKKK"
}

This is the value that I put in the ChartToken in order to be able to embed the chart. However, this value can only be used once and at each page load I need to obtain a new token to put in ChartToken.
Therefore I wrote a page to retrieve the token (that I wanted to use to send the value of the token to ChartToken):

<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Title Goes Here</title>

This is my web page

<form action="https://url.com/1/embeddedCharts" method="post" enctype="application/json">
<input name="apiToken" value="YYYYYYYY">
<input name="chartId" value="ZZZZZZZ">
<button>Send my data</button>
</form>

However, this page doesn't work. Maybe because I don't send the RAW header:
Authorization: Token YYYYYYYY

as I do in the Advanced REST client? I have read in some other forum that this is not possible in html, because I cannot define a custom header. Is this true?
Or maybe because
enctype="application/json"

doesn't actually replace
Content-Type: application/json

that I use the Advance REST client?
Or maybe because I don't write this page in the back-end server? How would I do that?
So, the solution to my problem would be to know:
1) How to write the POST request to obtain the token for the chart.
2) Where to write the request, if in the back-end.
3) How to pass the value to my front-end page, essentially to ChartToken.
Please, consider that I can only write a bit of html for front-end pages and I don't know much about web architectures. The easiest for me would be to have a full example with all the indications.
Thanks a lot.

A: I found a way to make the POST request from a jquery script within the html front-end page:

<!DOCTYPE html>

        <meta charset="utf-8" />
        <title></title>

  <button type="button" onclick="getReportTokenJS(apiToken, reportId, width, height, containerId);">generate embedded report</button>

Now, I would need to know how to pass values for reportId and apiToken to the jquery script variables. Please, consider that I found this example somewhere, so I don't really know how to program in jquery. A full working example modifying the code I provide here would be to only way to show me how to do.


text:
Q: Server rejects one request but accepts another. Why? I am making two HTTP GET requests to my (server) webservice in Java from a PHP website I am developing currently. I use the same function for making the GET requests. Server rejects one request & returns null as response while it accepts the other one & returns the correct response. Both these GET requests when tried from Google Chrome's extension POSTMAN returns correct response.
Why is server acting so weird like this?? For the request that server rejected, it says No 'Access-Control-Allow-Origin' header is present on the requested resource. Why is it so??? So, this means for the request that the server accepted, this particular header is present. I am confused.

A: The Access-Control-Allow-Origin is some kind of security-header sent by the server to prevent your server being called by random other servers but all processing of these headers is left to the client side. This means that your client-library (your webbrowser for example) checks if the domain currently visited is present in the Access-Control-Allow-Origin-Header. POSTMAN bypasses these checks (since it cannot currently visit any domain) and therefore always returns the response.
What you should check to prevent this issue from happening is that you always include the client-side-domain in Access-Control-Allow-Origin (or simply use * to allow all origins). Make sure to also include it in OPTIONS requests since they are often sent prior to POST or PUT requests.
If your requests are just failing on a certain HTTP-Method make sure to also set the Access-Control-Allow-Methods-Header to include all required HTTP-Methods (or simply use *)
Since POSTMAN always accepts your request it's a good tool to check if these headers are included in the response. If not, simply add them and you should be fine.


text:
Q: How do I specify the correct xpath / css selector for drop down list in Selenium (Python) I am trying to interact with a drop down list in Selenium and am currently getting having trouble in specifying the correct name / ID.
Xpath of the drop down list : //*[@id="post-2646"]/div2/div/div/div/p/select
URL of the drop down list: https://www.globalsqa.com/demo-site/select-dropdown-menu
My current code:
    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support.ui import Select
    from selenium.webdriver.support import expected_conditions as EC
    import time

    PATH =r"C:\Users\hey\OneDrive\Python\chromedriver.exe"
    driver = webdriver.Chrome(PATH)
    driver.get("https://www.globalsqa.com/demo-site/select-dropdown-menu")

    mySelect = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//select[contains(@id,'post-2646')")))).click()

    mySelect.select_by_visible_text('Taiwan')

This is the elements inspection page:

I've tried various other names / tags but am still getting the following timeout error message:

From my research, it seems that I'm inputting the wrong id name of the dropdown list in this line of code but I can't seem to be able to pinpoint the correct name / id to be used.
 mySelect = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//select[contains(@id,'post-2646')")))).click()

A: You are using wrong xpath. use below xapth for dropdwon
and use select_by_value() method for selecting option
as per https://www.globalsqa.com/demo-site/select-dropdown-menu page
option value for taiwan is TWN.
xpath=//div[@rel-title='Select Country']//select
mySelect = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//div[@rel-title='Select Country']//select')")))).click()

mySelect.select_by_value('TWN')

OR
 mySelect.select_by_visible_text('Taiwan, Province of China')


text:
Q: Linq group by 2 columns then and get last row for each group I have a table
Table1
PKID    FID     DATE            Col1        Col2
=================================================
1       1       01.01.2014      ABC     QWE
2       1       02.02.2014      BCD     QWE
3       1       03.03.2014      CDE     ASD
4       1       01.01.2014      DEF     AAS
4       2       02.02.2014      EFG     ASD
4       2       03.03.2014      FGH     ASD

I'm trying to group this table by PKID and FID and get the row corresponding to the latest date using LINQ.
I tried this:
Dim T1= From t In Table1 _
        Group By t.PKID, t.FID Into Group _
        Select PKID, FID, LastDate = Group.Max(Function(p) p.DATE)

now I have a table with PKID, FID and LastDate that looks like this:
T1
PKID    FID     LastDate
==========================
1       1       01.01.2014
2       1       02.02.2014
3       1       03.03.2014
4       2       03.03.2014

To this table I need to add the last 2 columns from Table1 like this
Result
PKID    FID     LastDATE        Col1    Col2
=================================================
1       1       01.01.2014      ABC     QWE
2       1       02.02.2014      BCD     QWE
3       1       03.03.2014      CDE     ASD
4       2       03.03.2014      FGH     ASD

In SQL it would be left joining on the three columns from T1. I know this isn't the best solution but this is all I got.
Don't know how to do this in LINQ, or if there is a better solution.
PS: Table1 has a Unique INDEX on (PKID, FID, DATE)

A: Found this
Dim ResultTable = From x In Table1 _
                  Group x By x.PKID, x.FID Into grp = Group _
                  Select New With {PKID, FID , .Record = (From x In grp Order By x.DATA Descending).FirstOrDefault()})

I have to test it, but it seems to work...


text:
Q: Unable to set property 'src' of undefined or null reference I am trying to use a button to change a picture on my webpage. When assigning a new value to the src attribute I have below error

Unable to set property 'src' of undefined or null reference

My code is below:

Introduction

Experience

Skills

Courses

Links

Contact

  <id ="navImg">

  </id>
  <button type="button" onclick="imgUpdate()">Another image</button></button>

A: You can fix it by not making up your own HTML tags. <id> is not a valid html tag, period. ID is an ATTRIBUTE for a tag, it is not tag itself:

And even if it WAS a tag, you'd be setting the src of the <id> tag, not the img, and effectively have
<id =navImg src="...">

A: After cleaning up a bit of your HTML, the JavaScript code works as expected

function imgUpdate(){
   var img = document.getElementById("navImg");   img.src="https://i.stack.imgur.com/6UgUs.jpg?s=328&g=1";
}

Introduction

Experience

Skills

Courses

Links

Contact

  <button type="button" onclick="imgUpdate()">Click for another image</button>


text:
Q: Eclipse unhandle loop exception I am new to Eclipse.
Every once in a while, I get this error message
http://i.stack.imgur.com/74ZP3.jpg
http://i.stack.imgur.com/FUJ8h.jpg
Please click on links to see images !
Thanks

A: This happens for two reasons,
1. improper updates of eclipse internal jar/s
2. Intermittent project issues
For 2, Go to project>Clean and clean all projects. (Ensure Build Automatically is selected) If persists restart eclipse.
For 1, close Eclipse IDE , navigate to eclipse folder location in your machine, eclipse>plugins>find org.eclipse.ui* folder/jar
remove that jar(take a backup and keep in another location)
Now start eclipse, It will update that jar which will solve the issue


text:
Q: How to prep a recipe, including tunable arguments? As you can see from my code, I am trying to include feature selection into my tidymodels workflow. I am using some kaggle data, trying to predict customer churn.
In order to apply processing to test and training data, I am baking the recipe after I am using the the prep() function.
However, if I want to apply tuning for the step_select_roc() functions top_p argument, I do not know, how to prep() the recipe afterwards. Applying it as in my reprex, results in an error.
Maybe I have to adapt my workflow and separate some recipe tasks to get the job done. What is the best approach to achieve this?
#### LIBS

suppressPackageStartupMessages(library(tidymodels))
suppressPackageStartupMessages(library(data.table))
suppressPackageStartupMessages(library(themis))
suppressPackageStartupMessages(library(recipeselectors))

#### INPUT

# get dataset from: https://www.kaggle.com/shrutimechlearn/churn-modelling
data <- fread("Churn_Modelling.csv")

# split data
set.seed(seed = 1972)
train_test_split <-
  rsample::initial_split(
    data = data,
    prop = 0.80
  )
train_tbl <- train_test_split %>% training()
test_tbl  <- train_test_split %>% testing()

#### FEATURE ENGINEERING

# Define the recipe
recipe <- recipe(Exited ~ ., data = train_tbl) %>%
  step_rm(one_of("RowNumber", "Surname")) %>%
  update_role(CustomerId, new_role = "Helper") %>%
  step_num2factor(all_outcomes(),
                  levels = c("No", "Yes"),
                  transform = function(x) {x + 1}) %>%
  step_normalize(all_numeric(), -has_role(match = "Helper")) %>%
  step_dummy(all_nominal(), -all_outcomes()) %>%
  step_corr(all_numeric(), -has_role("Helper")) %>%
  step_nzv(all_predictors()) %>%
  step_select_roc(all_predictors(), outcome = "Exited", top_p = tune()) %>%
  prep()

# Bake it
train_baked <- recipe %>%  bake(train_tbl)
test_baked <- recipe %>% bake(test_tbl)

A: You can't prep() a recipe that has tuneable arguments. Think of prep() as an analogy for fit() for a model; you can't fit a model if you haven't set the hyperparameters.
library(recipes)
#> Loading required package: dplyr
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union
#>
#> Attaching package: 'recipes'
#> The following object is masked from 'package:stats':
#>
#>     step

rec <- recipe( ~ ., data = USArrests) %>%
  step_normalize(all_numeric()) %>%
  step_pca(all_numeric(), num_comp = tune::tune())

prep(rec, training = USArrests)
#> Error in `prep()`:
#> ! You cannot `prep()` a tuneable recipe. Argument(s) with `tune()`: 'num_comp'. Do you want to use a tuning function such as `tune_grid()`?

Created on 2022-02-22 by the reprex package (v2.0.1)

A: Thanks to the help of Steven Pawley, I was able to integrate the tunable step_roc argument into my tidymodels model workflow. As Julia Silge mentioned, it is not possible to prep a recipe with tunable arguments. So if you still want to prep and bake your recipe, you can only do this as in the following example, after you have finalized your model and recipe:
suppressPackageStartupMessages(library(tidymodels))
suppressPackageStartupMessages(library(doParallel))
suppressPackageStartupMessages(library(recipeselectors))
suppressPackageStartupMessages(library(finetune))

data(cells, package = "modeldata")

cells <- cells %>% select(-case)
set.seed(31)
split <- initial_split(cells, prop = 0.8)
train <- training(split)
test <- testing(split)

rec <-
    recipe(class ~ ., data = train) %>%
    step_corr(all_predictors(), threshold = 0.9) %>%
    step_select_roc(all_predictors(), outcome = "class", top_p = tune())

# xgboost model
xgb_spec <- boost_tree(
    trees = tune(),
    tree_depth = tune(), min_n = tune(),
    loss_reduction = tune(),
    sample_size = tune(), mtry = tune(),
    learn_rate = tune(),
    stop_iter = tune()
) %>%
    set_engine("xgboost") %>%
    set_mode("classification")

# grid
xgb_grid <- grid_latin_hypercube(
    trees(),
    tree_depth(),
    min_n(),
    loss_reduction(),
    sample_size = sample_prop(),
    finalize(mtry(), train),
    learn_rate(),
    stop_iter(range = c(5L,50L)),
    size = 5
)

rec_grid <- grid_latin_hypercube(
    parameters(rec) %>%
        update(top_p = top_p(c(0,30))) ,
    size = 5
)

comp_grid <- merge(xgb_grid, rec_grid)

model_metrics <- metric_set(roc_auc)

rs <- vfold_cv(cells)

ctrl <- control_grid(pkgs = "recipeselectors")

cores <- parallel::detectCores(logical = FALSE)
cl <- makePSOCKcluster(cores)
registerDoParallel(cl)
set.seed(234)
rfe_res <-
    xgb_spec %>%
    tune_grid(
        preprocessor = rec,
        resamples = rs,
        grid = comp_grid,
        control = ctrl
    )
stopCluster(cl)

best <- rfe_res %>% select_best("roc_auc")

# finalize
final_mod <- finalize_model(xgb_spec, best)
final_rec <- finalize_recipe(rec, best)

# bakery
bake_test <- final_rec %>% prep() %>% bake(new_data = testing(split))
bake_train <- final_rec %>% prep() %>% bake(new_data = training(split))


text:
Q: Thunderbird removes leading spaces before XML/HTML tags, how can I disable that feature? The following is especially annoying on XML / HTML / XSL / etc user groups and mailing lists. When I create a new plain-text message and type the following message in Thunderbird 9.0.1:
Check this code:
<hello>
    <world />
</hello>

it will be received as
Check this code:
<hello>
<world />
</hello>

Oddly enough, this behavior doesn't happen when a sentence doesn't start with a <-symbol. In my own Sent-folder the leading spaces are removed too. When I send as HTML mail, the problem doesn't appear. Does anybody know of a way around this?
EDIT: result of extensive comment-discussion have been moved into the body of the text.


text:
Q: Button is not disabled at the initialization of page ,but gets disabled once you click it I made a very simple page , with an input field and a button.
I have to make button disabled when input field is empty . Once user clicks on it then input field will be cleared or reset .
My button is disabled once I click it. But its not disabled from the start.
My code is :
HMTL
<input type= 'text' [(ngModel)]="userName">

{{userName}}

<button[disabled]="userName==''(click)='resetUsername()'>RestUsername</button>

Typescript:
import {Component} from '@angular/core';

@Component({
    selector : 'app-server',
    templateUrl :'./server.component.html'
})
export class Servercl {
   username=''

  resetUsername = function(){
       this.userName='';
   }
}

Please tell where i am going wrong. Angular 4 is new to me.
I am making userName empty from the start . Dont understand what the problem is . Am i missing something?

A: Your variable name's parts are all in the lowercase: username. But your attached variable to the input and button is with name userName. So
username !== userName
-----------------^--

Try to make them the same. Also you have some error in the button template.
<button[disabled]="username === ''" (click)='resetUsername()'>RestUsername</button>


text:
Q: How to define the result of Solve as the variable Consider the operation
Solve[f[x,y,z] == 0, x]

I want to put the solutions for x obtained by this operation as the new variable. I tried to use ToString,
xsol[y_,z_] = ToString[Solve[f[x,y,z] == 0, x]],
but this didn't give the desired result. Can you please help me?

A: Are you using f[x,y,z] as a placeholder?  Or in your implementation is f[x,y,z] already defined?
Either way, a solution would be
xsol[y_, z_] = x /. Solve[f[x, y, z] == 0, x]

Out:
{InverseFunction[f, 1, 3][0, y, z]}

E.g. (f(x,y,z)=x^2-y+z)
Out:
{-√(y - z), √(y - z)}

If you'd like your answer to not have any brackets (as indicated in the comments),
and you know your solution to be monovalued then use Part to extract the answer.
xsol[y_, z_] = Solve[f[x, y, z] == 0, x][[1]]

Out:
InverseFunction[f, 1, 3][0, y, z]

E.g. (f(x,y,z)=x+y+z)
Out:
-y - z

Warning: If your solution is multivalued, this will return an incomplete answer.
E.g. (f(x,y,z)=x^2-y+z)
Out:
-√(y - z)

ToString is not a good solution, because then that expression will no longer be able to be used (unless you use ToExpression).
Note: Mathematica actually suggests a similar thing to what you're asking when you evaluate a Solve:

Not quite (as it doesn't assign it to an actual variable), but close.


text:
Q: Eclipse RCP application - custom splash screen I'm currently developing an Eclipse RCP application, in which I'm trying to implement a custom splash screen handler, sporting a progress bar (behavior similar to the default progress bar you can define in the .product definition) and multiple cycling background images.
After editing the extensions of the main application plugin this way:
[...]
<!-- install custom splash handler -->
<extension point="org.eclipse.ui.splashHandlers">
   <splashHandler
        class="com.example.application.splash.SlideShowSplashHandler"
        id="splash.slideshow">
   </splashHandler>
   <splashHandlerProductBinding
        productId="com.example.application.product"
        splashId="com.example.application.splash.slideshow">
   </splashHandlerProductBinding>
</extension>
<!-- define images (in plugin root directory) to be shown -->
<extension point="com.example.application.splashExtension">
     <splashExtension id="01" image="01_Splash2Ag.bmp"></splashExtension>
     <splashExtension id="02" image="02_Splash3Ag.bmp"></splashExtension>
     <splashExtension id="00" image="00_Splash1Ag.bmp"></splashExtension>
</extension>
[...]

I'm trying to implement the custom splashscreen handler class:
public class SlideShowSplashHandler extends AbstractSplashHandler {

    private List<Image> fImageList;
    private ProgressBar fBar;
    private final static String F_SPLASH_EXTENSION_ID = "com.example.application.splashExtension"; //NON-NLS-1
    private final static String F_ELEMENT_IMAGE = "image"; //NON-NLS-1
    private int imageIdx = 0;

    public SlideShowSplashHandler() {
        fImageList = new ArrayList<Image>(5);
    }

    /* (non-Javadoc)
     * @see org.eclipse.ui.splash.AbstractSplashHandler#init(org.eclipse.swt.widgets.Shell)
     */
    public void init(Shell splash) {
        // Store the shell
        super.init(splash);
            // Force shell to inherit the splash background
            getSplash().setBackgroundMode(SWT.INHERIT_DEFAULT);
        // Load all splash extensions
        loadSplashExtensions();
        // If no splash extensions were loaded abort the splash handler
        if (hasSplashExtensions() == false) return;
        // Create UI
        createUI(splash);
    }

    private boolean hasSplashExtensions() {
        if (fImageList.isEmpty()) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public IProgressMonitor getBundleProgressMonitor() {
       return new NullProgressMonitor() {

          @Override
          public void beginTask(String name, final int totalWork) {
            getSplash().getDisplay().syncExec(new Runnable() {
              public void run() {
                  fBar.setSelection(50);
              }
            });
          }

          @Override
          public void subTask(String name) {
            getSplash().getDisplay().syncExec(new Runnable() {
              public void run() {
                  if (fBar.getSelection() < 100) fBar.setSelection(fBar.getSelection() + 10);
                  if (imageIdx >= fImageList.size()) imageIdx = 0;
                  Image image = fImageList.get(imageIdx++);
                  getSplash().setBackgroundImage(image);
                  getSplash().setRedraw(true);
                  getSplash().redraw();
              }
            });
          }
        };
    }

    private void createUI(Shell shell) {

        Composite container = new Composite(shell, SWT.NONE);
        container.setLayout(new GridLayout(1, false));
        container.setLocation(5, 374);
        container.setSize(480, 15);

        /* Progress Bar */
        fBar = new ProgressBar(container, SWT.HORIZONTAL);
        fBar.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
        ((GridData) fBar.getLayoutData()).heightHint = 13;
        fBar.setMaximum(100);
        fBar.setSelection(25);

        /* Version Label */
        Label versionLabel = new Label(container, SWT.NONE);
        versionLabel.setLayoutData(new GridData(SWT.END, SWT.BEGINNING, true, false));
        //versionLabel.setFont(fVersionFont);
        //versionLabel.setForeground(fVersionColor);
        //versionLabel.setText(NLS.bind(Messages.SplashHandler_BUILD, "2.1 Nightly")); //$NON-NLS-1$

        /* Layout All */
        shell.layout(true, true);
    }

    private void loadSplashExtensions() {
        // Get all splash handler extensions
        IExtension[] extensions = Platform.getExtensionRegistry()
                .getExtensionPoint(F_SPLASH_EXTENSION_ID).getExtensions();
        // Process all splash handler extensions
        for (int i = 0; i < extensions.length; i++) {
            processSplashExtension(extensions[i]);
        }
    }

    /**
     * Parse the extension points with the images filename.
     */
    private void processSplashExtension(IExtension extension) {
        // Get all splash handler configuration elements
        IConfigurationElement[] elements = extension.getConfigurationElements();
        // Process all splash handler configuration elements
        for (int j = 0; j < elements.length; j++) {
            processSplashElements(elements[j]);
        }
    }

    /**
     * Create the images defined as extension points
     */
    private void processSplashElements(IConfigurationElement configurationElement) {

        String name = configurationElement.getAttribute(F_ELEMENT_IMAGE);
        ImageDescriptor descriptor = Activator.getImageDescriptor("/"+name);
        if (descriptor != null) {
            Image image = descriptor.createImage();
            if (image !=null) {
                fImageList.add(image);
            }
        }
    }

    public void dispose() {
        super.dispose();
        // Check to see if any images were defined
        if ((fImageList == null) ||
                fImageList.isEmpty()) {
            return;
        }
        // Dispose of all the images
        Iterator<Image> iterator = fImageList.iterator();
        while (iterator.hasNext()) {
            Image image = iterator.next();
            image.dispose();
        }
    }
}

Problem is that the progress bar just works, while the images are not shown. While debugging I could verify that the images are actually found and loaded, and correctly set in the shell; the shell just seems to not being redrawn. Am i missing something?=

A: I could solve the problem on linux and windows, but it did not work on macos/cocoa (in which the splash screen is looking "scrambled" on each image slideshow iteration).
Is was very simple indeed, just attaching an extra Composite between the splash shell and the container containing the widgets; then change the background image on the newly create container object.
private void createUI(Shell shell) {
    Composite bgcontainer = new Composite(shell, SWT.NONE); // new
    [...]
    Composite container = new Composite(bgcontainer, SWT.NONE);
    [...]
    fBar = new ProgressBar(container, SWT.HORIZONTAL);
    [...]
    Label versionLabel = new Label(container, SWT.NONE);
    versionLabel.setLayoutData(new GridData(SWT.END, SWT.BEGINNING, true, false));
    shell.layout(true, true);
}

@Override public IProgressMonitor getBundleProgressMonitor() {
return new NullProgressMonitor() {
    @Override public void beginTask(String name, final int totalWork) {
        getSplash().getDisplay().syncExec(new Runnable() {
            public void run() {
                    if (fBar != null) fBar.setSelection(40);
                    Image image = fImageList.get(imageIdx++);
                    bgcontainer.setBackgroundImage(image);
                    bgcontainer.setRedraw(true);
                    bgcontainer.update();
                }
            });
        }

    @Override public void subTask(String name) {
        final String n = name;
        getSplash().getDisplay().syncExec(new Runnable() {
            String taskname = n;
            public void run() {
                    if (fBar != null && fBar.getSelection() < 100)
                        fBar.setSelection(fBar.getSelection() + 10);
                    if (fBar.getSelection() == 60 || fBar.getSelection() == 80) {
                        if (imageIdx >= fImageList.size()) imageIdx = 0;
                        Image image = fImageList.get(imageIdx++);
                        bgcontainer.setBackgroundImage(image);
                        bgcontainer.setRedraw(true);
                        bgcontainer.update();
                    }
                 }
             });
         }
    };
}

A: I haven't tried your code, but when you make changes to a Control, it is not enough to call Control.redraw(), but you must also call Control.update().
Control.redraw() requests that a control should be redrawn, Control.update() actually redraws it. The later is needed when your code runs on the UI thread!


text:
Q: Flutter: Launch my other application from flutter application and get some data back Using flutter to launch other applications on both the platform (Android/iOS). I know we can use url_laucher to launch applications like Gmail or Google map.
Can it also be used for launching my own application?
If "YES", is it possible to get some data back from my other application to flutter application?
If "NO" then is there any other way to do this. My goal is to get the data (like a simple string) back from my other app.
NOTE: Constraint is that I have to use flutter Widgets or packages and not touch the native directories.

A: Yes, you can use url_launcher to launch your own application provided your application has appropriate url schemes defined.
No, you cannot get back any data by launching an application with url_launcher

Is there a way to achieve this only using flutter widgets and existing plugins?
Yes, only on android. There seems to be a flutter_share plugin that allows you to share data to other apps and receive data shared by other apps.
Hope that helps!


text:
Q: How can I prevent CakePHP HTML Helper from converting special characters to HTML entities? I am trying to get this result
<button>Title here (2) </button>

My problem is when i use
<?= $this->Html->link('<button>'.h($category->title).' ('.$cats[$key]['ArticleCount'].')</button>', ['action' => 'view', $category->id]) ?>

I get &lt instead of <.

A: You have to add escapeTitle => false to your Html->link() options array, as described in the documentation.


text:
Q: Tkinter scrolling frame: expand frame to fit content Canvas in one direction I'm trying to make a frame with a set height and a vertical scroll bar that responds to mouse scroll events. The frame needs to contain frames, so there's no built-in Tk widget I can use. Here's the Python 3 code I'm working with, derived from several related answers on here:
import tkinter as tk

class VertScrollingFrame(tk.Frame):
    def __init__(self, root):
        super().__init__(root)
        self.canvas = tk.Canvas(root)
        self.frame = tk.Frame(self.canvas)
        self.bar = tk.Scrollbar(root, orient = "vertical", command = self.canvas.yview)
        self.bar.lift(self.frame)
        self.canvas.configure(yscrollcommand = self.bar.set)

        self.bar.pack(side = "right", fill = "y")
        self.canvas.pack(side = "left", fill = 'both', expand = True)
        self.canvas.create_window(
            (4, 4),
            window = self.frame,
            anchor = "nw",
            tags = "self.frame",
        )
        #self.frame.pack()

        def on_cfg(_):
            self.canvas.configure(scrollregion = self.canvas.bbox("all"))
        self.frame.bind('<Configure>', on_cfg)

        def on_scroll(event):
            if event.delta:
                amount = round(-event.delta / 120)
            else:
                amount = {4: -1, 5: 1}[event.num] * 2
            self.canvas.yview_scroll(amount, "units")

        bind_keys = {'<MouseWheel>', '<Button-4>', '<Button-5>'}
        def scroll_bind(_):
            for key in bind_keys:
                self.canvas.bind_all(key, on_scroll)
        def scroll_unbind(_):
            for key in bind_keys:
                self.canvas.unbind_all(key)

        self.frame.bind('<Enter>', scroll_bind)
        self.frame.bind('<Leave>', scroll_unbind)

root = tk.Tk()
win = tk.Toplevel(root)
sf = VertScrollingFrame(win)
for _ in range(20):
    f = tk.Frame(sf.frame)
    for x in range(12):
        tk.Button(f, text = str(x)).pack(side = 'left')
    f.pack()
sf.pack()
root.mainloop()

I've filled the scrolling frame with a wide grid of buttons, and the canvas appears to be resizing horizontally to fit them, but the ScrollingFrame isn't. It just cuts off the right side of the content. How can I make the frame expand to fit its contents horizontally?
With the call to self.frame.pack() uncommented, I get a different incorrect result: the grid of buttons is strangely cropped both vertically and horizontally, and there's nothing to scroll.


text:
Q: React component with html text I want to render react components with html, and my react component must listen states, but I can`t do it..
{component} = ComponentText

I have something like this and this Array can be in different orders and different combinations, for example:
let result = ['

123', {component}, '

', {component}];

With "dangerouslySetInnerHTML", I have:
123[Object][Object]

Without "dangerouslySetInnerHTML":

123ComponentText

ComponentText

I`m looking for result like this:
123ComponentTextComponentText

And my states and events with this component must work well, Is it possible?

A: In React, you don't deal in HTML snippets like your result array, you deal in objects.
But you can use JSX to do something similar to what you want, just not with isolated bits of text in an array:
let result = [

123<Component />

, <Component />];

Live Example:

class Component extends React.Component {
  constructor(...args) {
    super(...args);
    this.state = {
      value: Math.floor(Math.random() * 1000)
    };
  }
  render() {
    return I'm a component, this.state.value = {this.state.value};
  }
}

let result = [

123<Component />

, <Component />];

ReactDOM.render(

{result}
,
  document.getElementById("root")
);

To illustrate that you're still dealing with objects despite using JSX, here's what that JSX transpiles to:
var result = [
    React.createElement(
        "div",
        null,
        React.createElement(
            "p",
            null,
            "123",
            React.createElement(Component, null)
        )
    ),
    React.createElement(Component, null)
];


text:
Q: How to fetch username of the user who is logged into AD domain on OSX using objective C Is there a way to find the username (User Principal Name or samaccountname) of the user who is using my app and is logged into an AD domain?
Can we also find which domain is the user connected to programmatically?
dsconfigad -show command line does display the domain but not the username.
I cannot rely on NSUsername() or NSFullUserName() functions as user can manually change those.
Any help will be appreciable.


text:
Q: These Images are off center Trying to make contact information, the images are appearing far to the right of the page, when I want it centered, I've tried to put a right margin and padding, but it didn't work, I've removed code, but it didn't do anything. I don't know what else to try.

.contactinfo {
  float: left;
  border: 3px solid #189AB4;
  border-radius: 10px;
  text-align: center;
  margin-top: 20px;
  margin-left: 200px;
  width: 70%;
}

.border {
  float: left;
  background-color: #189AB4;
  margin-left: 125px;
  width: 75%;
  height: 4px;
}

a.contacts {
  background-color: transparent;
  border: none;
  width: 50px;
  height: 50px;
  margin-right: 50px;
  float: left;
}

a.contacts:hover {
  background-color: transparent;
  border: none;
  width: 50px;
  height: 50px;
  margin-right: 50px;
  float: left;
}

a {
  padding-top: 20px;
  text-decoration: none;
  text-align: center;
  background-color: #75E6DA;
  border-right: 2px #189AB4 solid;
  color: #189AB4;
  width: 100px;
  height: 40px;
  float: left;
}

A: Gave your content class a display: flex and then set your contactNav class a margin: 0 auto
of course this might not be the exact solution since i'm not sure what else is supposed to be within those div blocks that are empty.

.contactinfo {
  float: left;
  border: 3px solid #189AB4;
  border-radius: 10px;
  text-align: center;
  margin-top: 20px;
  margin-left: 200px;
  width: 70%;
}

.border {
  float: left;
  background-color: #189AB4;
  margin-left: 125px;
  width: 75%;
  height: 4px;
}

a.contacts {
  background-color: transparent;
  border: none;
  width: 50px;
  height: 50px;
  margin-right: 50px;
  float: left;
}

a.contacts:hover {
  background-color: transparent;
  border: none;
  width: 50px;
  height: 50px;
  margin-right: 50px;
  float: left;
}

a {
  padding-top: 20px;
  text-decoration: none;
  text-align: center;
  background-color: #75E6DA;
  border-right: 2px #189AB4 solid;
  color: #189AB4;
  width: 100px;
  height: 40px;
  float: left;
}

/* Changes Made Below */

.content {
  display: flex;
}

.contactNav {
  margin: 0 auto;
}

A: You can do this;
.contactNav {
   display: flex;
   justify-content: center;
}

That might help


text:
Q: How do I view logs for a failed cron job in App Engine? One of the daily cron jobs I defined in cron.yaml failed on my live webapp2 app.
Is there a way to view say standard error output, stack traces, or logs in general from App Engine cron jobs?

A: These do show up in the logs.  Perhaps do a regex search for 'AppEngine-Google', as that will show up in the user-agent header for cron jobs and taskqueues.

A: With the consolidated logs, you should be able to look at the time your job was supposed to run.  Crashes should be in the logs, but you need to hook up logging for it to show up there.


text:
Q: AWS Node.js Lambda: Promise reject does not return custom error, resolve works I'm running a AWS Lambda function in Node.js 14, bound to a REST API in API Gateway with LAMBDA_PROXY.
Consider this simplified Pseudo Code for index.js:
exports.handler = async function (event, context) {
    if (event.body.myParam === '1') {
        // Works!
        return {
            statusCode: 302,
            headers: {
                Location: 'https://iam.aredire.ct'
            }
        };
    } else if (event.body.myParam === '2') {
        // Works! 403 - {"message":"You are not allowed to do that!"}
        return {
            statusCode: 403,
            body: JSON.stringify({
                message: 'You are not allowed to do that!'
            })
        };
    } else if (event.body.myParam === '3') {
        const jwt = require('jsonwebtoken');
        const token = 'ey...';
        const pubKey = '-----BEGIN PUBLIC KEY----- ...';

        // Some promise
        return new Promise(function (resolve, reject) {
            // Some async call
            jwt.verify(token, pubKey, function (err, decoded) {
                if (err) {
                    // gets logged
                    console.log(err);

                    // 502 - {"message": "Internal server error"}
                    return reject({
                        statusCode: 403,
                        body: JSON.stringify({
                            message: 'No valid token'
                        })
                    });

                    // 502 - {"message": "Internal server error"}
                    return reject(JSON.stringify({
                        statusCode: 403,
                        body: {
                            message: 'No valid token'
                        }
                    }));
                }
                // Works! 200 - {"message":"Works!"}
                resolve({
                    statusCode: 200,
                    body: JSON.stringify({
                        message: 'Works!'
                    })
                });
            });
        });
    }
}

Please see the comments in the code snippets. Do you have any idea why resolve() and return work as expected but reject() always returns 502 - {"message": "Internal server error"}? I want that the requester actually gets a 403 - {"message": "No valid token"}?
I read about JSON.stringifying the whole error object, but that does not help.
Cloudwatch raises this error:
ERROR   Invoke Error
{
    "errorType": "Error",
    "errorMessage": "{\"statusCode\":403,\"body\":{\"message\":\"No valid token\"}}",
    "stack": [
        ...
    ]
}

A: See Error Handling in Other Services:

API Gateway treats all invocation and function errors as internal errors. If the Lambda API rejects the invocation request, API Gateway returns a 500 error code. If the function runs but returns an error, or returns a response in the wrong format, API Gateway returns a 502 error code. To customize the error response, you must catch errors in your code and format a response in the required format.

You should resolve the promise, rather than reject it, to indicate to API Gateway that it completed normally, and include the relevant 4xx statusCode and body to indicate to your client (not API Gateway) that it represents an application-level failure.


text:
Q: Shortest distance between two lines in 3-dimensional space Can someone explain to me how to solve this question?
Find the shortest distance between the lines
$L_1 = \left\{t \begin{bmatrix} 1\\ 1\\ 1\end{bmatrix} : t \in \mathbb{R}\right\}$ and $L_2 = \left\{s \begin{bmatrix} 1\\ 2\\ 3\end{bmatrix} + \begin{bmatrix} 1\\ 0\\ 0\end{bmatrix}: s \in \mathbb{R}\right\}$
Thanks

A: The difference vector is
$$
d = L_2(s) - L_1(t)
= s (1,2,3) + (1,0,0) - t (1,1,1)
= (s - t + 1, 2s - t, 3s - t)
$$
Then
$$
q = \lVert d \rVert^2 = d^2 = (s-t+1)^2 + (2s - t)^2 + (3s - t)^2
$$
Then the gradient is
$$
q_s =2(s-t+1)+ 4 (2s-t) + 6(3s-t) = 28s-12t + 2 \\
q_t = -2(s-t+1)-2(2s-t) -2(3s-t) = -12s+6t-2
$$
It vanishes for
$$
\left(
\begin{array}{rr|r}
 28 & -12 & -2 \\
-12 &   6 &  2
\end{array}
\right)
\to
\left(
\begin{array}{rr|r}
 16 &  -6 &  0 \\
-12 &   6 &  2
\end{array}
\right)
\to
\left(
\begin{array}{rr|r}
 16 &  -6 &  0 \\
  4 &   0 &  2
\end{array}
\right)
\to \\
\left(
\begin{array}{rr|r}
 16 &  -6 &  0 \\
  1 &   0 &  1/2
\end{array}
\right)
\to
\left(
\begin{array}{rr|r}
  0 &  -6 &  -8 \\
  1 &   0 &  1/2
\end{array}
\right)
\to
\left(
\begin{array}{rr|r}
  1 & 0 &  1/2 \\
  0 & 1 &  4/3
\end{array}
\right)
$$
So $s = 1/2$ und $t = 4/3$. This gives
$q = d^2 = (1/6)^2 + (-1/3)^2 + (1/6)^2 = 1/18 + 1/9 = 3/18 = 1/6$
and $d = 1/\sqrt{6}$.

(Large version)

A: The Euclidean distance between the two lines is
$$\left\|s \begin{bmatrix} 1\\ 2\\ 3\end{bmatrix} - t \begin{bmatrix} 1\\ 1\\ 1\end{bmatrix} + \begin{bmatrix} 1\\ 0\\ 0\end{bmatrix}\right\| = \left\|\begin{bmatrix} 1 & -1\\ 2 & -1\\ 3 & -1\end{bmatrix} \begin{bmatrix} s\\ t\end{bmatrix} - \begin{bmatrix} -1\\ 0\\ 0\end{bmatrix}\right\|$$
Minimizing this Euclidean distance is a least-squares problem. The mininimizer of $\| A x - b\|$ is given by the solution to the so-called normal equations $A^T A x = A^T b$. Since
$$\begin{bmatrix} 1 & -1\\ 2 & -1\\ 3 & -1\end{bmatrix}^T \begin{bmatrix} 1 & -1\\ 2 & -1\\ 3 & -1\end{bmatrix} = \begin{bmatrix} 14 & -6\\ -6 & 3\end{bmatrix}, \qquad{} \begin{bmatrix} 1 & -1\\ 2 & -1\\ 3 & -1\end{bmatrix}^T \begin{bmatrix} -1\\ 0\\ 0\end{bmatrix} = \begin{bmatrix} -1\\ 1\end{bmatrix}$$
the normal equations give us the following system of equations
$$\begin{bmatrix} 14 & -6\\ -6 & 3\end{bmatrix} \begin{bmatrix} s\\ t\end{bmatrix} = \begin{bmatrix} -1\\ 1\end{bmatrix}$$
whose solution is $\begin{bmatrix} s\\ t\end{bmatrix} = \begin{bmatrix} \frac{1}{2}\\ \frac{4}{3}\end{bmatrix}$. The minimum Euclidean distance between the two lines is, thus,
$$\left\|\frac{1}{2} \begin{bmatrix} 1\\ 2\\ 3\end{bmatrix} - \frac{4}{3} \begin{bmatrix} 1\\ 1\\ 1\end{bmatrix} + \begin{bmatrix} 1\\ 0\\ 0\end{bmatrix}\right\| = \left\|\begin{bmatrix} \frac{1}{6}\\ -\frac{1}{3}\\ \frac{1}{6}\end{bmatrix}\right\| = \frac{1}{\sqrt{6}}$$

A: First take the cross product of the two direction vectors: $<1,1,1>\times<1,2,3>=<1,-2,1>$. We can
normalize to the unit vector $\frac{1}{\sqrt6}<1,-2,1>$
The minimum distance will be the length of the scalar projection of any line segment joining L1 and L2 onto this unit vector. We have the points (0,0,0) on L1 and (1,0,0) on L2, which are joined by the vector <1-0,0-0,0-0>=<1,0,0>. The length of the scalar projection will then be the magnitude of the dot product of <1,0,0> and $\frac{1}{\sqrt6}<1,-2,1>$, which is $\frac{1}{\sqrt6}$


text:
Q: Object serialization query and class path I had a question in regards to serializing an object and being able to retrieve the object in a different program. The problem with retrieving an object in a different program is that the program cant find the object(symbol).
From what I understand this serialized object needs to be on a classpath.
(Still a student and not sure exactly what it means to place an object on a class path)
My question is how do you place an object on a classpath using NetBeans 7.0.1?

A: Basically you should have the serialized Java Class exported as a JAR file. The consuming App, the one which deserializes it, should have this jar on its class path in order to deserialize it... Btw, you are de/serializing an Object i.e. a Class Instance, not the class itself.
Netbeans project-classpath


text:
Q: call post method without submit button causing infinite loop I have a form from which I want latitude and longitude and I want want load this without submit button.
<form method="post" id="myform" action="" >
  <input type='hidden' value='' name='latitude'/>
  <input type='hidden' value='' name='longitude'/>
</form>

I tried
document.getElementById("myForm").submit();

But it causes infinite loop and I want it on the same page so I am not giving action.
I add this function but still not working.
function send_data(lat, lon) {
    document.getElementById('place_lon').innerHTML = lat + ' : ' + lon;
   //     $("input[name='lattitude']").val(lat);
    //    $("input[name='longitude']").val(lon);
    $j = jQuery.noConflict();

    $j(document).ready(function() {
        $j('#myform').submit(submit_myform);
   });

    function submit_myform() {
             $j.ajax({
                url: window.location.href,
                type: 'POST',
                data: $j(this).serialize(),
                dataType: 'json', //data type of Ajax response expected from server
                success: myform_success //callback to handle Ajax response and submit to Paypal
            });
            return false;//prevent normal browser submission, since the form is submitted in the callback
    }

    function myform_success(response) {
        //this is called whenever the ajax request returns a "200 Ok" http header
        //manipulate the form as you wish
        $("input[name='latitude']").val(lat);
        $("input[name='longitude']").val(lon);
       // $j('#lattitude').val(lat);
      //  $j('#longitude').val(lon);
        //submit the form (to the form's action attribute)
        document.forms['#myform'].submit();
    }

}

A: What happens is that as soon as form is loaded it submits itself, then loads again and submits etc.
Try using AJAX request to send data to the server.
$.ajax({
  type: "POST",
  url: window.location.href,
  data: $('#myForm').serialize()
});


text:
Q: os.popen().read() hangs until I type "exit" in the console Code:
import platform
import socket
import webbrowser
import psutil
from subprocess import check_output
import re
import urllib.request
import winreg as reg
from datetime import datetime
import os
import time
import sys
import subprocess

outfile = open('platform.txt', "w")

hardwareList = ["Platform: " + platform.system()]

hardwareList.append("Operating System: " + platform.platform())

info = os.popen('cmd /k systeminfo | find "Original Install Date"').read()
stripInfo = info.replace('Original Install Date:     ','')
hardwareList.append("OS Installation Date: " + stripInfo.strip())

hardwareList.append("Processor: " + platform.processor())

hardwareList.append("Qty Physical CPU's: %s " % psutil.cpu_count(logical=False))

hardwareList.append("Qty Logical CPU's: %s" % psutil.cpu_count(logical=True))

hardwareList.append("Qty Cores: %s" % (psutil.cpu_count(logical=True)/psutil.cpu_count(logical=False)))

memory = psutil.virtual_memory()
hardwareList.append("RAM: " + str("{:3.2f}".format(memory[0]/1024/1024/1024)))

diskUsage = psutil.disk_usage('C:/')
total = "{:4.2f}".format((diskUsage[0]/1024/1024/1024))
avail = "{:4.2f}".format((diskUsage[2]/1024/1024/1024))
used = "{:4.2f}".format((diskUsage[1]/1024/1024/1024))

hardwareList.append("Total Capacity: %s " % total + "MB")

hardwareList.append("Total Free: %s " % avail + "MB")

hardwareList.append("Total Used: %s " % used + "MB")

clocksp = str(check_output("wmic cpu get MaxClockSpeed"))
clocksp1 = re.findall(r'\d+',clocksp)
clocksp2 = (float(clocksp1[0])/1000)
hardwareList.append("Clockspeed: %s" % clocksp2 + " GHz")

hardwareList.append("Network Data:")

hardwareList.append("HostName: " + socket.gethostname())

hardwareList.append("FQDN: " + socket.getfqdn())

hardwareList.append("IP Address: " + socket.gethostbyname(socket.gethostname()))

dbTypes = ['MongoDB','MSSQLSERVER','MySQL','postgresql-x64-9.5']
for db in dbTypes:
    try:
        dbInfo = psutil.win_service_get(db).as_dict()
        hardwareList.append("Database Name: " + dbInfo['display_name'] + ", status=" + dbInfo['status'])
    except:
        search = dbInfo['display_name'].find(db)
        if search != -1:
            hardwareList.append(search)
        else:
            hardwareList.append("Database Name: " + db + ", status=Not installed")

softwareList = []
for dir in os.listdir("C:\Program Files"):
    if os.path.isdir("C:\Program Files"+"\\"+dir):
        hardwareList.append("Software: " + dir)

for ins in hardwareList:
    outfile.write(str(ins) + "\r\n")

outfile.close()

So what's happening here is that the code is hanging up and failing to complete (it produces a blank text file with no data called 'platform.txt') until I type 'exit' in the console.  I want this to run without human intervention and I don't know python well enough to figure out how to overcome this problem.
Help me make it run without having to type "exit" in the console.
Note: I've tried subprocess, but got lost in all the difficult to read manual documentation, and other solutions provided on StackOverflow didn't do what I wanted it to do.
I believe it is failing at this line:
    info = os.popen('cmd /k systeminfo | find "Original Install Date"').read()
But can't be sure.
I'm using Python 3.5

A: The /k option to cmd means "Carries out the command specified by string but remains" - in other words, you are explicitly telling it to behave in this undesired manner.  Try /c instead - "Carries out the command specified by string and then terminates".


text:
Q: PHP rand() exclude certain numbers I have this:
<?php  $n = rand(1,1600); echo $n ?>

I want to exclude from random numbers let's say 234, 1578 ,763 , 1274 and other numbers. How would I do that?

A: Check if the number is one that you don't want, if it is get a new random number.
function getRandomNumber() {
    do {
        $n = mt_rand(1,1600);
    } while(in_array($n, array(234,1578, 763, 1274)));

    return $n;
}

A: Always use cryptographically strong algorithms for generating random numbers:
/**
 * @param int   $from     From number
 * @param int   $to       To number
 * @param array $excluded Additionally exclude numbers
 * @return int
 */
function randomNumber($from, $to, array $excluded = [])
{
    $func = function_exists('random_int') ? 'random_int' : 'mt_rand';

    do {
        $number = $func($from, $to);
    } while (in_array($number, $excluded, true));

    return $number;
}

var_dump(randomNumber(1, 100));
var_dump(randomNumber(1, 10, [5, 6, 7, 8]));
var_dump(randomNumber(1, 100, range(10, 90)));

I'd also recommend using the paragonie/random_compat library for compatibility in case of using multiple PHP versions.

A: <?php

while( in_array( ($n = mt_rand(1,1600)), array(234, 1578 ,763 , 1274) ) );

A: Try like this
do {
    $n = rand(1,1600);

} while(in_array($n, array(234, 1578 ,763 , 1274 ));
echo $n;

A: Or avoid making loops with random (possibly infinite) running time:
/**
 * Returns a random integer between $min and $max (inclusive) and
 * excludes integers in $exarr, returns false if no such number
 * exists.
 *
 * $exarr is assumed to be sorted in increasing order and each
 * element should be unique.
 */
function random_exclude($min, $max, $exarr = array()) {

    if ($max - count($exarr) < $min) {
        return false;
    }

    // $pos is the position that the random number will take
    // of all allowed positions
    $pos = rand(0, $max - $min - count($exarr));

    // $num being the random number
    $num = $min;

    // while $pos > 0, step to the next position
    // and decrease if the next position is available
    for ($i = 0; $i < count($exarr); $i += 1) {

        // if $num is on an excluded position, skip it
        if ($num == $exarr[$i]) {
            $num += 1;
            continue;
        }

        $dif = $exarr[$i] - $num;

        // if the position is after the next excluded number,
        // go to the next excluded number
        if ($pos >= $dif) {
            $num += $dif;

            // -1 because we're now at an excluded position
            $pos -= $dif - 1;
        } else {
            // otherwise, return the free position
            return $num + $pos;
        }
    }

    // return the number plus the open positions we still had to go
    return $num + $pos;
}

This function chooses a random position and walks the exclusion array to find the free position. It's running time depends on the amount of numbers to exclude. If you want to exclude certain ranges, you may want to adapt the algorithm to take this into account.

A: Another solution for this could be as follows:
function random_number($min, $max, $exclude)
{
      $number = rand($min, $max);

  if(in_array($number, $exclude))
  {
      random_number($min, $max, $exclude);
  } else {
      return $number;
  }
}

$number = random_number(1,10, [2,5,6]);

A: As the volume of "blacklisted" integers approaches the volume of the full range of integers, it becomes increasingly compelling to take the advice of @regenschein.
A non-iterative approach might look like this:
$range = range(1, 1600);
$blacklist = [234, 1578, 763, 1274]; // 4 blacklisted versus 1600 full range is NOT compelling
$valids = array_diff($range, $blacklist);
echo array_values($valids)[rand(0, count($valids) - 1)];
// or
echo $valids[array_rand($valids)];
// the two approaches use different randomizers

Or if you'd be just as happy shuffling, you could do:
$blacklist = [234, 1578, 763, 1274];
$range = range(1, 1600);
$valids = array_diff($range, $blacklist);
shuffle($valids);
echo $valids[0];

*Note array_diff() is particularly great if you want to pass multiple blacklist arrays -- just comma-separate them.
For example:
var_export($valids = array_diff(range(1, 100), range(5, 50), range(61, 99), [55]));

Output:
array (
  0 => 1,
  1 => 2,
  2 => 3,
  3 => 4,
  50 => 51,
  51 => 52,
  52 => 53,
  53 => 54,
  55 => 56,
  56 => 57,
  57 => 58,
  58 => 59,
  59 => 60,
  99 => 100,
)

A: I know this is a bit old,but I think what the op tries to do is shuffle the integers. If so the following method is better
$array = array(1,2,3,4,5,6,7);
shuffle($array);

This code will randomize the order of the array's exact elements without repetition and return the result inside the array itself.

A: You could create an array with valid numbers.
Then, your random number generation should return the index into that array.

A: If you don't have too many numbers to exclude, it is easier and faster to just retry if you find an unwanted number:
$n = 0;
while (in_array($n, array(0, 234, 1578 ,763 , 1274))) {
  $n = rand(1,1600);
}

echo $n;


text:
Q: Invisible ActiveX that takes a string I need to adapt a simple function (let's say) int printText(string) written using an MFC library (this function prints the text on a particular printer whose driver lib is completely developed by MFC), to two applications developed the first in LabView and the second in Java (Eclipse RCP).
I've thought that an ActiveX component is the right choice that could fit well in both applications, but I don't know where to begin.
Is there any one that can guide me in developing this simple ActiveX without dealing with all the flexibilities (i.e complexities) of ActiveX world? My component should be invisible, nothing more than a print method that takes a string (and eventually another init method to initialize the printer).

A: This greatly depends on the style in ActiveX is written in. Some frameworks can access them and other not. As far as I am aware, the following tools will help you (we use all of them in different contexts):

*

*SWT (Has an OLE interface, good for ActiveX controls running in YOUR process)

*Com4J (Great stuff for working with ActiveX components having its own thread, like remoting Word or Outlook)

*JNative (Good for calling simple DLL function)


text:
Q: Android Gradle Build Exception packageReleaseResources step on Android Library Has anyone seen an error like this before?
I've tried to look the the Android Source for where the null pointer exception could be coming from but it makes no sense. The message is not really helping at all.
It happens when I do a ./gradle clean build on the CLI.
Project structure is like
app/
 - build.gradle
shared/

16:13:22.388 [DEBUG] [org.gradle.execution.taskgraph.AbstractTaskPlanExecutor] Task worker [Thread[main,5,main]] finished, busy: 1.482 secs, idle: 0.019 secs
16:13:22.396 [ERROR] [org.gradle.BuildExceptionReporter]
16:13:22.399 [ERROR] [org.gradle.BuildExceptionReporter] FAILURE: Build failed with an exception.
16:13:22.399 [ERROR] [org.gradle.BuildExceptionReporter]
16:13:22.399 [ERROR] [org.gradle.BuildExceptionReporter] * What went wrong:
16:13:22.401 [ERROR] [org.gradle.BuildExceptionReporter] Execution failed for task ':shared:packageReleaseResources'.
16:13:22.401 [ERROR] [org.gradle.BuildExceptionReporter] > java.lang.NullPointerException (no error message)
16:13:22.402 [ERROR] [org.gradle.BuildExceptionReporter]
16:13:22.403 [ERROR] [org.gradle.BuildExceptionReporter] * Exception is:
16:13:22.404 [ERROR] [org.gradle.BuildExceptionReporter] org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':shared:packageReleaseResources'.
16:13:22.404 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
16:13:22.405 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
16:13:22.405 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
16:13:22.405 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64)
16:13:22.405 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
16:13:22.406 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:42)
16:13:22.406 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
16:13:22.406 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
16:13:22.406 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
16:13:22.407 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.AbstractTask.executeWithoutThrowingTaskFailure(AbstractTask.java:289)
16:13:22.407 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.executeTask(AbstractTaskPlanExecutor.java:79)
16:13:22.409 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:63)
16:13:22.410 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:51)
16:13:22.411 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$1.run(DefaultTaskPlanExecutor.java:33)
16:13:22.411 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.internal.Factories$1.create(Factories.java:22)
16:13:22.412 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.cache.internal.DefaultCacheAccess.longRunningOperation(DefaultCacheAccess.java:198)
16:13:22.412 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.cache.internal.DefaultCacheAccess.longRunningOperation(DefaultCacheAccess.java:266)
16:13:22.413 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.cache.internal.DefaultPersistentDirectoryStore.longRunningOperation(DefaultPersistentDirectoryStore.java:135)
16:13:22.413 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.changedetection.state.DefaultTaskArtifactStateCacheAccess.longRunningOperation(DefaultTaskArtifactStateCacheAccess.java:95)
16:13:22.413 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:31)
16:13:22.414 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:86)
16:13:22.414 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:29)
16:13:22.414 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:61)
16:13:22.414 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.execution.DefaultBuildExecuter.access$200(DefaultBuildExecuter.java:23)
16:13:22.415 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.execution.DefaultBuildExecuter$2.proceed(DefaultBuildExecuter.java:67)
16:13:22.415 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
16:13:22.415 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:61)
16:13:22.415 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:54)
16:13:22.416 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:166)
16:13:22.416 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:113)
16:13:22.416 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:81)
16:13:22.416 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:64)
16:13:22.416 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.launcher.cli.ExecuteBuildAction.run(ExecuteBuildAction.java:33)
16:13:22.416 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.launcher.cli.ExecuteBuildAction.run(ExecuteBuildAction.java:24)
16:13:22.417 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:35)
16:13:22.417 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
16:13:22.417 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.launcher.cli.RunBuildAction.run(RunBuildAction.java:50)
16:13:22.417 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.internal.Actions$RunnableActionAdapter.execute(Actions.java:171)
16:13:22.417 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:201)
16:13:22.418 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:174)
16:13:22.418 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:170)
16:13:22.418 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:139)
16:13:22.418 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:33)
16:13:22.418 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:22)
16:13:22.419 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.launcher.Main.doAction(Main.java:46)
16:13:22.419 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.launcher.bootstrap.EntryPoint.run(EntryPoint.java:45)
16:13:22.419 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.launcher.Main.main(Main.java:37)
16:13:22.419 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:50)
16:13:22.419 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:32)
16:13:22.420 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.launcher.GradleMain.main(GradleMain.java:23)
16:13:22.420 [ERROR] [org.gradle.BuildExceptionReporter] Caused by: java.lang.NullPointerException
16:13:22.420 [ERROR] [org.gradle.BuildExceptionReporter]    at com.android.ide.common.res2.DataSet.updateWith(DataSet.java:407)
16:13:22.420 [ERROR] [org.gradle.BuildExceptionReporter]    at com.android.ide.common.res2.ResourceSet.updateWith(ResourceSet.java:48)
16:13:22.420 [ERROR] [org.gradle.BuildExceptionReporter]    at com.android.build.gradle.tasks.MergeResources.doIncrementalTaskAction(MergeResources.groovy:136)
16:13:22.421 [ERROR] [org.gradle.BuildExceptionReporter]    at com.android.build.gradle.internal.tasks.IncrementalTask.taskAction(IncrementalTask.groovy:85)
16:13:22.421 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:63)
16:13:22.421 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.doExecute(AnnotationProcessingTaskFactory.java:236)
16:13:22.421 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:212)
16:13:22.422 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.execute(AnnotationProcessingTaskFactory.java:223)
16:13:22.422 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:201)
16:13:22.422 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:533)
16:13:22.422 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:516)
16:13:22.423 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
16:13:22.440 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
16:13:22.440 [ERROR] [org.gradle.BuildExceptionReporter]    ... 49 more
16:13:22.441 [ERROR] [org.gradle.BuildExceptionReporter]
16:13:22.441 [LIFECYCLE] [org.gradle.BuildResultLogger]
16:13:22.441 [LIFECYCLE] [org.gradle.BuildResultLogger] BUILD FAILED
16:13:22.444 [LIFECYCLE] [org.gradle.BuildResultLogger]
16:13:22.445 [LIFECYCLE] [org.gradle.BuildResultLogger] Total time: 24.788 secs


text:
Q: Бейджы в вордпресс Есть код
add_filter('woocommerce_sale_flash', 'vs_change_sale_content', 10, 3);
function vs_change_sale_content($content, $post, $product){
   $content = ''.__( 'On Sale', 'woocommerce'  ).'';
   return $content;}

Этот код выполняет вывод бейджика товара в Wordpress, как сделать так чтобы он выводил не On Sale а выводил разницу между скидкой и суммой , допустим мой товар стоит 5000 рублей а скидка 2000 рублей и надо чтобы выводило Вы экономите 3000 рублей. как мне назначить значения discount - price , я пытался сделать так и наоборот и выводит значение 0
Помогите пожалуйста )


text:
Q: How can I convert this jQuery code to JavaScript? I want convert following working jQuery code into JavaScript
$(document).ready(function(){
    $("#txt1").keydown(function(event){
        var keyPress=String.fromCharCode(event.keyCode);
        var Keycode=event.keyCode;
        alert("KeyPress : "+keyPress)
        alert("KeyCode : "+Keycode)
    })
})

and I am trying this to replace this code with JavaScript
document.getElementById("txt1").onkeydown=function(event){
    var keyPress=String.fromCharCode(event.keyCode);
    var Keycode=event.keyCode;
    alert("KeyPress : "+keyPress)
    alert("KeyCode : "+Keycode)
}

and this above code not working.

A: Try this:
window.onload = function() {
  document.getElementById("txt1").addEventListener("keydown", function(e) {
    keyPress = String.fromCharCode(e.keyCode);
    keyCode = e.keyCode;
    alert("KeyPress : " + keyPress)
    alert("KeyCode : " + keyCode)
  }, false);
}


text:
Q: Invoking a mule non-webservice flow from Activiti I have a JMS mule flow, which will read messages from a queue and process them. I would like to invoke this flow from a process in Activiti. I am using a remote mule instance. From what I understand, to invoke a mule flow in a remote mule instance, I have to use web service. How can I use web service in this case?
I am using the community edition of mule.
Thanks

A: Assuming you know the Web Service URL for your remote Mule instance, you would need to do one of two things:

*

*Create a serviceDelegate class that calls the Web Service endpoint and call this from Activiti

*Use the Camel module with Activiti to handle the call to Mule

Personally I am a fan of using Camel for this sort of thing since the hard work has already been done for you and it is a relatively simple matter to create a camel route and call it from an Activiti service task (there are even BPMN extension attributes built into the latest versions of Activiti that make this even easier).
Other things to consider.
Is this a fire and forget (i.e. one way) call or are you expecting a response? If you are expecting a response, will it be synchronous or asynchronous? All these factors will impact how you model the BPMN flow to properly integrate the Mule flow.


text:
Q: Header(Location) command is skipped My header(Location) command does not execute.
Program simply skips that line.
On my code I have tried a lot of options.
With / without ob_start,
header command with ' or with ".
Space either side of : or both sides.
Execution continues as there is no header command.
I put some alerts before and after. I saw all of them.
...
}

else

{

ob_start();

header('Location:ordersummary.php');

}

...
This is my code. Copy and pasted. Simple and clean.
When I copy/paste target address to browser, page shows up without any problem.


text:
Q: Autocomplete using data from mysql in play? I'm working on a project using the play! framework and I'm currently stuck trying to figure out how to connect a basic jquery autocomplete to use mysql database as the datasource and retrieve information from it. Has anyone tried this before ? Thanks.

A: With jqueryui autocomplete, you just have to set an input field with a special class "autocomplete" :
<input type="text" class="ui-state-default autocomplete" name="object.name" value="" />

Then you can use this jquery code to setup the autocomplete
$(document).ready(function(){
  $('input.autocomplete').each( function() {
    var $input = $(this);
    // Set-up the autocomplete widget.
    $(this).autocomplete({
        minLength: 3,
        source : function(req, resp) {
          $.getJSON("@{MyController.getObjects()}?term=" + req.term , req, function(data) {
            var suggestions = [];
            $.each(data, function(i, val) {
              var obj = {};
              obj.label = val.name;
              obj.id = val.id;
              suggestions.push(obj);
            });
            resp(suggestions);
          });
        }
      });
  });
});

Here you call the method getObjects on controller "MyController". This method looks like
public static void getObjects(final String term) {
    renderJSON(MyObject.findByName(term, AUTOCOMPLETE_MAX));
}

where "findByName" is a method in your model object that search objects by name. AUTOCOMPLETE_MAX is a const that defines the maximum number of objects you want to retrieve.
The controller method getObjects return a json object that is called "val" in the javascript. Note that you have to map values from this object to an object with a "label" and an "id" that can be managed by jquery autocomplete.
With this solution, you will get back the object name in your controller validation method. I like this solution because you can then search the object by name in the controller allowing a user to choose something wihtout using the autocomplete list. You will then validate the name in the controller validation method.
You have another solution based on id on lunatech site : http://www.lunatech-research.com/archives/2011/07/05/jquery-ui-ajax-autocomplete-playframework

A: Try using jquery-UI autocomplete.
http://jqueryui.com/demos/autocomplete/
This could help
In the auto complete jquery UI, you can give input(sources) as string, array or javascript callback.
In your case, you can use callback as the source and can use ajax to get the data from the mysql.
I haven't tried it, but I guess it should work.


text:
Q: Flex custom components, events and scope I'm starting to give up on the Flex forums so I'l re-post here and see how things go. Long time lurker, first time poster ;-)
I'm trapping keyboard events on the stage and dispatching custom events through a framework (Mate, though I don't know that this is an important issue), but I'm pretty confused by the scope. The structure is:
--application (traps keyboard events and dispatches custom event
 --  mainPanel (receives dispatched events but mainCalendar (a child element)
     is null on debugging. Obviously if I try to call a public method on
     mainCalendar it errors out, even though it's a child of mainPanel.
     However, mainCalendar is NOT null IF I use
     FlexGlobals.topLevelApplication.mainPanel.mainCalendar.
     Outerdocument and parentDocument do not expose mainCalendar either, BTW

     --  mainCalendar (a custom component inside mainPanel with public methods.
         Creation policy is 'all' and it's visible and exists long before I
         trap any keystrokes at the top level)

Could someone take a minute and explain why the mainCalendar is out of scope when mainPanel receives a custom event, even though mainCalendar is a child of mainPanel. Is there a better way to manage the events so I don't have to always address the component via the topLevelApplication?
Thanks

A: (creating answer so this question could be marked as answered)
Usually, when reference to component is null and it should not, this means component isn't created yet. This might have place before application initialize event or if component's parent isn't visible and not validated.


text:
Q: python docx.opc.exceptions.PackageNotFoundError: Package not found when opening Document I want to open a .docx file with function Document(). But it always returns:
docx.opc.exceptions.PackageNotFoundError: Package not found at '/home/chaomaer/PycharmProjects/demo/lab1/book1.docx'
However, when I change the function to  open(), it works well.
I want to know "why?"
from docx import Document
import os
document = open('book1.docx')
# document = Document('book1.docx')
print document.read()

A: I know a simple solution
I work in a ubantu Os
when the docx raise the error, try copy the file that can not be opened in a new file within MS word. It works for me
if someone knows the deep reason. I woud to be appreciate to you.

A: First install pip install python-docx
And then change the code following:
from docx import Document
import os
#document = open('book1.docx')
document = Document('book1.docx')
for p in document.paragraphs:
    print p.text

It works for me. Hope this will help.
EDIT:
You should create docx file with MS or other suitable editor. My advice - use google docs if you have account. Creating file with touch command in the terminal doesn't help.

A: I've noticed that if I create the Word document by right-clicking in Windows Explorer and selecting New > Word Document, I will forever get the PackageNotFoundError on that document. If, instead, I open Microsoft Word and create the document through there, it works just fine.

A: This happened to me. Turned out that the word document I tried to open with docx was corrupted.

A: I found that if I had the word document open at the same time - even if I wasn't doing anything to it, it still threw this error. Closing the word document solved it for me.

A: Writing Word Documents
The following instruction where found in the book "automatetheboringstuff".

*

*To create your own .docx file, call docx.Document() to return a new, blank Word Document object.

*The add_paragraph() document method adds a new paragraph of text to the document and returns a reference to the Paragraph object that was added.

*When you're done adding text, pass a filename string to the save() document method to save the Document object to a file.

*This will create a file named helloworld.docx in the current working directory.

Enter the following into the interactive shell:
>>> import docx
>>> doc = docx.Document()
>>> doc.add_paragraph('Hello world!')
<docx.text.Paragraph object at 0x0000000003B56F60>
>>> doc.save('helloworld.docx')

Seems that many of us where creating document with name, as we called the open object function, where as the docx library creates an empty file without name when open object function is called. location and Name needs to be added while saving the document.

A: At first, I was facing the same issue but not on all Docx files only a few files. then I printed the local path of each file and found out that whenever I hit the PackageNotFoundError issue. Most of the time these files are temp Docx files and can't be open/read even from Microsoft applications.
Below is my code:
def _RsDocx_(SearchString, Path):
flag = 0
index = 0
doc = docx.Document(Path)
for para in doc.paragraphs:
    index += 1
    if SearchString in para.text:
        flag = 1
        break
if flag != 0:
    print('String', SearchString, 'Found In Line: ', index, 'File Path: ', Path)

I already Imported Docx lib and calling this def from the main


text:
Q: Vectorising a function over pandas - unknown window length/index range I have a dataframe as below.
          signal   positions.  rates
Date
2018-01-02  0      NaN         1.2065
2018-01-03  0      0.0         1.2023
2018-01-04  0      0.0         1.2065
2018-01-05  1      1.0         1.2045
2018-01-08  0.    -1.0         1.1973
2018-01-09  0      0.0         1.1932
2018-01-10  0      0.0         1.1992
2018-01-11  1      1.0         1.2017
2018-01-12  1      0.0         1.2137
2018-01-15  0     -1.0         1.22

Based on the position column, i wish to create a new columns called entryRate.
All rows between a position of 1 and -1 are to have the same rate : the rate when position = 1. For ex:
          signal    positions   rates   entryRate
Date
2018-01-02  0       NaN         1.2065  0.0000
2018-01-03  0       0.0         1.2023  0.0000
2018-01-04  0       0.0         1.2065  0.0000
2018-01-05  1       1.0         1.2045  1.2045
2018-01-08  0      -1.0         1.1973  1.2045
2018-01-09  0       0.0         1.1932  0.0000
2018-01-10  0       0.0         1.1992  0.0000
2018-01-11  1       1.0         1.2017  1.2017
2018-01-12  1       0.0         1.2137  1.2017
2018-01-15  0      -1.0         1.2277  1.2017

Currently am looping over the rows to implement this. The condition is formed on the signal column that stays = 1 between position =1 and position=-1
dat['entryRate'] = 0
        i=0
        while(i<len(dat)):
            if (dat.iloc[i,0]==1):
                entry = dat.iloc[i,2]
                while (dat.iloc[i,0]==1):
                    dat.iloc[i,3]=entry
                    i+=1

                    #end of dataframe cond
                    if(i==len(dat)):
                        break

                #update one more row after end of while loop, don't update if end of dataframe is reached
                if i<len(dat):
                    dat.iloc[i,4]=entry

            else:
                i+=1

Any nice way to vectorize this function? I can't put a finger on what to use - apply, merge asof, etc.
Appreciate any and all suggestions guys :)

A: I am sure there is a better vectorised solution, but I think this one is better than what you have
entryRate = 0.0
for i, row in df.iterrows():
    if row['positions'] == 1.0:
        entryRate = row['rates']
        df.loc[i,'entryRate'] = entryRate
    elif row['positions'] == -1.0:
        df.loc[i,'entryRate'] = entryRate
        entryRate = 0.0
    else:
        df.loc[i,'entryRate'] = entryRate

Result:
            signal  positions   rates  entryRate
Date
2018-01-02       0        NaN  1.2065     0.0000
2018-01-03       0        0.0  1.2023     0.0000
2018-01-04       0        0.0  1.2065     0.0000
2018-01-05       1        1.0  1.2045     1.2045
2018-01-08       0       -1.0  1.1973     1.2045
2018-01-09       0        0.0  1.1932     0.0000
2018-01-10       0        0.0  1.1992     0.0000
2018-01-11       1        1.0  1.2017     1.2017
2018-01-12       1        0.0  1.2137     1.2017
2018-01-15       0       -1.0  1.2200     1.2017


text:
Q: How to change image in LongListSelector SelectionChanged method? I have a LongListSelector in my Windows Phone app. The LLS has a Image and TextBlock for each item. How can I change image when a user change the selection? What should i write in my SelectionChanged method?
<phone:LongListSelector x:Name="MainLongListSelector" ItemsSource="{Binding Items}" SelectionChanged="MainLongListSelector_SelectionChanged">
    <phone:LongListSelector.ItemTemplate>
          <DataTemplate>
              <StackPanel Orientation="Horizontal">
                  <Image Name="PlayPause" Source="/Assets/transport.play.png"/>
                  <StackPanel>
                      <TextBlock Text="{Binding LineOne}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
                  </StackPanel>
               </StackPanel>
          </DataTemplate>
    </phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>

A:     <phone:LongListSelector x:Name="MainLongListSelector" DataContext="{Binding listData}" IsGroupingEnabled="False" SelectionChanged="MainLongListSelector_SelectionChanged_1">
            <phone:LongListSelector.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Image Name="PlayPause" Source="{Binding ImgUrl}" Height="100" Stretch="Fill"/>
                        <StackPanel>
                            <TextBlock Text="{Binding ImgText}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
                        </StackPanel>
                    </StackPanel>
                </DataTemplate>
            </phone:LongListSelector.ItemTemplate>
        </phone:LongListSelector>

Behind the XAML:
    ObservableCollection<LongListData> listData = new ObservableCollection<LongListData>();

    listData.Add(new LongListData() { ImgText = "Image1", ImgUrl = new Uri("Images/1.jpg", UriKind.Relative) });
    listData.Add(new LongListData() { ImgText = "Image2", ImgUrl = new Uri("Images/2.jpg", UriKind.Relative) });
    listData.Add(new LongListData() { ImgText = "Image3", ImgUrl = new Uri("Images/3.jpg", UriKind.Relative) });
    listData.Add(new LongListData() { ImgText = "Image4", ImgUrl = new Uri("Images/4.jpg", UriKind.Relative) });

    MainLongListSelector.ItemsSource = listData;

In SelectionChanged Method
    private void MainLongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var res = (sender as LongListSelector).SelectedItem as LongListData;
        int index = listData.IndexOf(res);
        //mark 1
        var newData = new LongListData() { ImgText = res.ImgText, ImgUrl = new Uri("Images/2.jpg", UriKind.Relative) };
        listData.RemoveAt(index);
        listData.Insert(index, newData);
    }

Define a class in C# code
    public class LongListData
    {
        public Uri ImgUrl { get; set; }
        public string ImgText { get; set; }
    }

You can use images Randomly or according to your need at 'mark1' in the code.


text:
Q: Usage of RXJava map in Kotlin? Why is this complaining about a miss-type? map supposed to transfor the value of an observable to another, but it's expecting me to return an observable from the map
override fun fetchExercises(): Observable<List<Exercise>> {
    return FirebaseDatabase.getInstance()
        .getReference("exercises")
        .observeSingleEvent()
        .map { snapshot: DataSnapshot? -> object: List<Exercise>
            // Error here
            return listOf<Exercise>()
        }
    }

fun DatabaseReference.observeSingleEvent(): Observable<DataSnapshot> {
    return Observable.create(object : Observable.OnSubscribe<DataSnapshot> {
        override fun call(subscriber: Subscriber<in DataSnapshot>) {

            val valueEventListener = object: ValueEventListener {
                override fun onDataChange(snapshot: DataSnapshot?) {
                    subscriber.onNext(snapshot)
                    subscriber.onCompleted()
                }

                override fun onCancelled(error: DatabaseError?) {
                    subscriber.onError(FirebaseDatabaseThrowable(error))
                }
            }

            addListenerForSingleValueEvent(valueEventListener)
        }
    })
}

A: @zsmb13 has pointed out the correct answer right there. Here, I would like to comment on some mistake made in your lambda expression.
.map { snapshot: DataSnapshot? -> object: List<Exercise>
        // Error here
        return listOf<Exercise>()
}

object: List<Exercise> here is not a valid syntax since the body goes after an -> sign inside the lambda expression. We do not specify the return type inside the body.
Also, the return here means to return from fetchExercises() as described in Kotlin docs:

A return statement without a label always returns from the function declared with the fun keyword. This means that a return inside a lambda expression will return from the enclosing function, whereas a return inside an anonymous function will return from the anonymous function itself.

As what @zsmb13 said, return is not needed in most of the case. If you really want it(for flow control), you can use qualified returns:
//This is answer from @zsmb13
.map { snapshot: DataSnapshot? ->
    return@map listOf<Exercise>()
}

A: This part of your code
.map { snapshot: DataSnapshot? -> object: List<Exercise>

says that the type of the snapshot parameter that this lambda receives is DataSnapshot? -> object: List<Exercise> (which actually isn't a valid function type, that would be DataSnapshot? -> List<Exercise>).
I believe what you actually wanted to do is the following, a snapshot parameter that just has the type DataSnapshot:
.map { snapshot: DataSnapshot? ->
    listOf<Exercise>()
}

The return type of the lambda doesn't have to be specified here, it will just be inferred. You also don't need to use the return keyword in a lambda, because the last expression in it is what's returned.