text:
Q: Variable is not setting inside for loop I am trying to iterate over a set of numbers of 4 sig figs, padded with zeros if number is small like 1 = 0001, I echo !filenum:~-4! which gives me the expected results of 0001, 0002, etc. But when I try to set a variable to !filenum:~-4! it does not work
@echo off
setlocal EnableDelayedExpansion
for /L %%i in (1, 1, 10) do (
     echo %%i
     set filenum=0000%%i
     echo filenum !filenum!
     echo !filenum:~-4!
     set f = !filenum:~-4!
     IF "!f!"=="" ECHO MyVar is NOT defined
)

A: I found the problem, the space after f when assigning the value change the name of the var to "f ". I got to remember that spaces matter in batch scripts


text:
Q: How to install Ubuntu server 19.10 on orange pi 3? I have a Orange pi 3 , I have tried to install Ubuntu server 19.10 (arm64 version ) on my board but it was unsuccessful:
I wrote ubuntu-19.10-live-server-arm64.iso on a TF card via balena Etcher. Then I put the card in its slot and powered on the board, but Das u-boot just booted default android tv (installed from factory on board) and didn't boot the fedora image. I deleted Das u-boot and android tv partition using fdisk on orange pi modified version of ubuntu 16.04 Xenial. I retried booting Ubuntu server 19.10 from card but the board just showed processor (Allwinner H6) logo and froze in this level.
I tried installing ubuntu mate 18.04.2 arm64 version but it had same result as ubuntu server.
At the end I took the TF card out an when I restart the borad saw the allwinner logo again that means the borad didn't recognized those medias as bootable media!
I really need help installing Ubuntu 19.10 server on my board.
note: all of iso files hashes are checked and they were healthy files

A: Did you use the images as supplied by orange pi or did you take the images from the main website and just chose the arm image?
http://www.orangepi.org/downloadresources/OrangePi3/2019-01-23/orangepi3_b0c3dac8d3483dab6eb392b0a9.html
This is the image you should be using.
Mind you. Orange pi offers very limited support so if you are up for it it might be better to customise something from scratch.

redpajama_set_name: RedPajamaStackExchange


text:
Q: 'TestString' is not declared. It may be inaccessible due to its protection level. (BC30451) I am trying out some on the fly code compilation using the VBCodeProvider class. What I want to be able to do is modify a public variable in my assembly in the code.
I have a Public TestString As String = "" in my application.
This is the code I am using to compile:
    Dim codeProvider As New VBCodeProvider()
    Dim optParams As New CompilerParameters
    optParams.ReferencedAssemblies.Add("MyAssembly.exe")
    optParams.ReferencedAssemblies.Add("system.windows.forms.dll")
    optParams.CompilerOptions = "/t:library"
    optParams.GenerateInMemory = True
    Dim results As CompilerResults = codeProvider.CompileAssemblyFromSource(optParams, RichTextBox1.Text)

    If results.Errors.Count > 0 Then
        Dim sb As New StringBuilder("Compilation Failed with the following error(s)" + CR_LF + CR_LF)
        For Each CompErr As CompilerError In results.Errors
            sb.Append(String.Format("Line {0} - {1} ({2}){3}", CompErr.Line, CompErr.ErrorText, CompErr.ErrorNumber, CR_LF))
        Next
        MessageBox.Show(sb.ToString, "Compile Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    Else
        Dim assy As System.Reflection.Assembly = results.CompiledAssembly
        Dim exeinstance As Object = assy.CreateInstance("Script")
        Dim typ As Type = exeinstance.GetType
        Dim method As MethodInfo = typ.GetMethod("Main")
        method.Invoke(exeinstance, Nothing)
    End If

This is the code in my textbox:
Imports System
Imports MyAssembly

Class Script
    Sub Main()
       TestString="foo"' <-- This line fails compilation
    End Sub
End Class

The error I get is 'TestString' is not declared. It may be inaccessible due to its protection level. (BC30451)

A: Just like normal VB.NET, as well as adding a reference, you have to Imports the relevant namespace, or specify it fully. (You've edited the question to now include this.)
After inserting your code into a new Console project in VS2008 (because that's what I had open) and adjusting for my assembly names, I saw the same as you.
I fixed it by adding Public to the default Module Module1.


text:
Q: Why Doesn't dt[,ncol(dt)] Return Column Contents? I've edited this question based on comments by @akrun (thank you!), realizing I didn't accurately ask my question.
I'm confused why the following doesn't return the contents of the last column in a data table.
> dt <- data.table(A=c(10,10,10),B=c(20,20,20),C=c(30,30,30))
> dt[,ncol(dt)]
[1] 3

If I use with=F it behaves as I would expect, returning the last column as a data table
> dt[,ncol(dt),with=F]
   C
1: 30
2: 30
3: 30

This returns the same result as dt[,3] which makes sense. But why is it not true that dt[,ncol(dt)] = dt[,3]? From ?data.table,

When j is a vector of column names or positions to select (as in data.frame). There is no need to use with=FALSE anymore.

Doesn't ncol(dt) return a vector of column positions, a vector of length one? Why doesn't dt[,ncol(dt)] return the contents of the last column?
Thanks for your help!

A: We need drop = FALSE for data.frame
df[,ncol(df), drop = FALSE]

as by default it is TRUE if we check the ?Extract

x[i, j, ... , drop = TRUE]

For the data.table, we need with = FALSE
 dt[, ncol(dt), with = FALSE]

and it is mentioned in the ?data.table help

When j is a character vector of column names, a numeric vector of column positions to select or of the form startcol:endcol, and the value returned is always a data.table. with=FALSE is not necessary anymore to select columns dynamically. Note that x[, cols] is equivalent to x[, ..cols] and to x[, cols, with=FALSE] and to x[, .SD, .SDcols=cols].


text:
Q: Multithreaded Python script calling C++ subprocess: speed/performance issue I am currently writing a Python script to run simultaneous simulations of sporting events (let's say for argument's sake that they are tennis matches; it could be other sporting events or even option prices from a given list of stocks). At the moment, my script allocates a thread for each event, calling a function which contains a subprocess call (via POpen) to a C++ executable (i.e. the simulation). There is also a logging instance that is shared between the threads to collect status messages relating to the simulation output and some other functions manipulating that output, as well as error messages when there is faulty input data.
Somewhat predictably, I find that the simulation time for each event increases as the total number of events increases. I have been looking at a couple of options to alleviate this problem:

*

*Initially, I thought that the issue arose from the Global Interpreter Lock (GIL) and tried to wrap my C++ code using the Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS macros to release the GIL. I never got it to work, always getting an error message that a tState couldn't be found.

*I considered using multiprocessing (or concurrent.futures) instead of threading. But I can see at least two problems with this change of approach. First, there could be situations where the number of events I have to simulate concurrently well exceeds the number of cores available on my computer (e.g. there could be 30-40 concurrent tennis matches at a given time). Second, there could be issues in trying to maintain a common logging instance across several concurrent processes.

So, I have two sets of questions:

*

*Is the "thread macros" solution viable in this case? If so, what could I be doing wrong to get this missing tState error message?

*Would multiprocessing (or concurrent.futures) resolve my problem, despite the constraints I have outlined? If not, what other option(s) could be available?


text:
Q: node.js & moment : different results based on how value is passed? I get different output based on how values are passed to moment. How are they different?
var moment = require('moment');
var aa = "1392018037000";
var bb = "1392057925366";
console.log(moment(aa).from(bb));
console.log(moment(1392018037000).from(1392057925366));

output:
a few seconds ago
11 hours ago

A: This is a string:
var aa = "1392018037000";

This is an integer:
var aa = 1392018037000;

According to moment documentation:

Similar to new Date(Number), you can create a moment by passing an
  integer value representing the number of milliseconds since the Unix
  Epoch (Jan 1 1970 12AM UTC).

So proper way would be to use an integer. String behaves differently in Javascript, mostly because it would need to call parseInt function, and that has different way of parsing integers.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt


text:
Q: Running external command with user input in C I want to show the output of the Linux command dialog --menu from my C program so that the user can select an option from the menu.  Also, the last line of output from the program is the option the user selected, so I need to capture that.
I've tried using popen() and system() to accomplish this, and looked on the web, but couldn't find anything that led to a successful result.
If I can't find a way to use dialog, I will have to use a much simpler approach (a simple "Type your choice and press enter") and it won't be as cool.
Thank you in advance,
Brian

A: The dialog command prints the result of the user's selections on stderr.  This means you will have to capture stderr, not stdout.  This is a bit tricky.  I'm going to go test this myself, but my guess is that the easiest thing to do is use popen like this:
FILE *dialog = popen("(dialog --menu plus other arguments >/dev/tty) 2>&1");

Then you can read from the dialog file (provided it's not NULL of course).
This works because the argument of popen is actually passed to an invocation of sh.  This means that popen really runs sh -c <argument of popen> so all the standard shell redirections work.  So you use parenthesis to get exactly what you want, which is for the dialog program itself to send its output to its controlling terminal, and for its stderr to be redirected to the place where you can read it with popen.
There is another method that has the same disadvantages as the popen solution, and has the additional disadvantage of requiring you to open and read another file after dialog finishes.  But it has the advantage of simplicity.  Unfortunately it also requires you to be able to write to the filesystem, and the most natural place to do that (/tmp) is fraught with security issues relating to making sure someone else doesn't somehow hijack your file.  That method is to do system("dialog --menu plus other arguments 2>temp_file");.  Then you read from temp_file when it's done.
These are both a bit ugly, especially since dialog takes a lot of arguments that are likely to have shell metacharacters in them.  So even if the above work, I would highly recommend using a combination of pipe, fork, execvp, fdopen, and waitpid to get the result you're after.
A skeleton for that would look something like this:
#include <stdio.h>
#include <stddef.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>

int main(int argc, const char *argv[])
{
   const char *dia_args[] = {
      "dialog",
      "--output-fd",
      NULL,
      "--menu",
      "Hi there",
      "60", "15", "15",
      "t1", "i1",
      "t2", "i2",
      "t3", "i3",
      "t4", "i4",
      "t5", "i5",
      NULL
   };
   int pipefds[2];

   if (pipe(pipefds) < 0) {
      perror("pipe failed");
      return 1;
   } else {
      const pid_t child = fork();
      if (child < 0) {
         perror("fork failed");
         return 1;
      } else if (child == 0) {
         char pipefdstr[60];
         close(pipefds[0]);
         if (snprintf(pipefdstr, sizeof(pipefdstr) - 1, "%u", pipefds[1]) < 0) {
            perror("snprintf failed");
            return 1;
         } else {
            pipefdstr[sizeof(pipefdstr) - 1] = '\0'; /* Protect against bugs in snprintf */
            dia_args[2] = pipefdstr;
            execvp(dia_args[0], dia_args);
            perror("Unable to exec dialog command");
            return 1;
         }
      } else { /* child > 0 */
         FILE *dialog = fdopen(pipefds[0], "r");
         char inbuf[200];
         int waitresult = 0;
         if (dialog == NULL) {
            perror("Unable to fdopen");
            kill(child, SIGKILL);
            return 1;
         }
         close(pipefds[1]);
         while (fgets(inbuf, sizeof(inbuf) - 1, dialog)) {
            inbuf[sizeof(inbuf) - 1] = '\0';
            printf("Got [%s] from dialog.\n", inbuf);
         }
         fclose(dialog);
         if (waitpid(child, &waitresult, 0) < 0) {
            perror("waitpid failed");
            return 1;
         }
         if (!WIFEXITED(waitresult) || (WEXITSTATUS(waitresult) != 0)) {
            fprintf(stderr, "dialog exited abnormally.");
            return 1;
         }
      }
   }
   return 0;
}

A: well, i had done that pretty well. see the code sample below:
fp = fopen(SCRIPT_FILE, "w+");
fprintf(fp,
    "#!/bin/sh\\n\\n"
    "dialog --clear --title \""BRAND_INFO"\""
    " --inputbox \""TITLE"\\n\\n"
    "Please input the name[/tmp/input]:\" "
    BOX_HEIGHT" "BOX_WIDTH" 2> "RESULT_FILE"\n");
fclose(fp);
system("bash "SCRIPT_FILE);
fp = fopen(RESULT_FILE, "rt");
// here read the results from the RESULT_FILE
//    into which dialog had written the results.
...

a little boring plus a little perfromance loss but doable for all components of dialog such as checklist and menu etc.
You could control all details of the scripts which would be stored in the SCRIPT_FILE, and the overall action and flow controlling is simple.

A: I'm sure I'm asking for a firestorm of criticism but nevertheless here is the basic idea. I didn't check this for compiler errors and didn't supply the header files. It's just a code snippet I whipped up while taking a drink.
Basically, you fork(), in the child process redirect stderr and call exec(), call waitpid() in the parent process and get the return value of "dialog," and if there was no error read the file to which you redirect stderr.
pid_t pid;
char cmd[] = "dialog";
char *args[] = {"dialog", "--menu", NULL};
int status;
int fd;

if((pid = fork()) == 0)
{
  /* child */

  /* I believe dialog prints to stderr the answer chosen
   * also you should check the return value of open()
   */
  fd = open("some_file_name", O_WRONLY | O_CREAT | O_TRUNC, 0);

  close(STDERR_FILENO);

  dup(fd);

  execvp(cmd, args);
  perror("execvp()");
  exit(1);
}
else if(pid < 0)
{
  perror("fork()");
  exit(1);
}
else
{
  /* parent */

  /* you should also check the return of waitpid()
   * this is just for example
   */
  waitpid(pid, &status, 0);

  /* if everything was ok then status has the return value
   * also the file "some_file_name" should have the output
   */
}

A: You could use pipes to get the standard output and give the child application input (controlled by your main application). You would need to fork and use a conventional exec rather than popen or system, however.


text:
Q: sign of expression Can I show that the following expression is always positive,
$$b-a+a(\log a - \log b)$$
here $a>b$ and both $a$ and $b$ are positive numbers between 0 and 1. I have plotted this expression and I can see that it is positive but I want to show it analytically. Can anyone help ?

A: Divide by b (remember b > 0) and substitute x = a/b to get
1 - x + x Log[x] > 0

Then
Minimize[1 + x Log[x] - x, x]
(* {0, {x -> 1}} *)

Or analytically:
$$\frac{\delta}{\delta x}\left(1-x+x\log{x}\right)=-1+\log{x}+\frac{x}{x}=\log{x}$$
Which is $0$ when $x=1$.
$$f\left(x=1\right)=1-1+1\log{1}=0$$
But x <= 1 is not allowed because a > b.  The expression is positive for x > 1.


text:
Q: Redirect to Route from Saga using React Router v6 I'm using redux saga & react router v6 and I want to redirect to a route from one of my sagas, is there a way to do it ?

A: There are multiple options

1 - Sending the navigate method as part of dispatched redux action
// component
const navigate = useNavigate()
dispatch({type: FOO, navigate})

// saga
yield takeEvery(FOO, function*(action) {
  action.navigate('/foo')
})

Pros:

*

*You are using the navigate method which is recommended by the react-router team

*The API is unlikely to change

Cons

*

*You have access to the navigate method only in specific sagas that received such action

*You have unserializable data in your actions

2 - Another option is to store the navigate method in some way. E.g. you can create a dummy react component that will get the navigate method through useNavigate hook and then store it in some "global" variable. See this SO answer for a possible solution:
https://stackoverflow.com/a/70002872/2347716
This deals with the the cons from previous solution, but there are still some issues:

*

*You need your React tree to render at least once before you have access to the navigate method

*You are adding non-view complexity to your view layer by introducing the dummy component

3 - There is another solution, similar to what we had with react-router 5 that deals with the issues in the previous solution. It is to use the history object. It is not documented since its unstable, but there is a HistoryRouter implementation as part of the react-router-dom package. See https://github.com/remix-run/react-router/releases/tag/v6.1.1
import {unstable_HistoryRouter as HistoryRouter} from 'react-router-dom'
import { createBrowserHistory } from "history";
const history = createBrowserHistory()

// saga setup
sagaMiddleware.runSaga(rootSaga, history);

// react
<HistoryRouter history={history} />

The issue with this solution is that it is unstable because it might have some issues with some of React 18 features. Personally I prefer it since it solves everything else and we can deal with React 18 issues once its actually released and we know what they are.

A: My solution
// "HistoryRouter" implementation
import * as React from 'react'
import type {BrowserHistory} from 'history'
import {Router} from 'react-router-dom'

export interface HistoryRouterProps {
    history: BrowserHistory
    basename?: string
    children?: React.ReactNode
}

export function HistoryRouter({
    basename,
    children,
    history,
}: HistoryRouterProps) {
let [state, setState] = React.useState({
    action: history.action,
    location: history.location,
})

React.useLayoutEffect(() => history.listen(setState), [history])

return (
    <Router
         basename={basename}
         children={children}
         location={state.location}
         navigationType={state.action}
         navigator={history}
   />
)
}

// Use
import {createBrowserHistory} from 'history'
export const history = createBrowserHistory()

ReactDOM.render(
   <HistoryRouter history={history}>
       <Routes>
           <Route path="login" element={<LoginComponent />} />
           <Route path="register" element={<RegisterComponent />} />
           <Route path="*" element={<HomeComponent />} />
      </Routes>
   </HistoryRouter>
, root)

// call history push in file saga
function* fetchLoginSaga(action: FetchLoginRequest) {
    try {
         yield call(history.push, "/home")
    } catch (e: any) {

    }
}

A: I present my solution to the problem, maybe it is a bit convoluted but it is very clean and useful:
All of us will have a parent component in the routes, in my case I have called it App, and we can imagine that we will have this component connected to redux, therefore the following tree would remain:
index.js > Provider > Router > App (with Outlet) > Child Route.
That means that we can create a yield put that changes a props in the parent component, in my case App, which will contain a useEffect that will launch the navigate:
import { useEffect } from 'react'
import { Outlet, useNavigate } from "react-router-dom";

const AppContainer = ({  url }) => {
    const navigate = useNavigate()

    useEffect(()=>{
        if (url) {
            navigate(url)
        }
    }, [url])

    return (

            <Outlet />

     )
}

export default AppContainer;

Now whenever I want to navigate from the sagas I simply have to execute a yield put, in this way the props url is modified and the useEffect is launched that sends me to the requested url.
Since my SPA system is a bit complex, I'll leave you to solve that part of connecting the dispatch with the component

A: There is an option that works well for me. You should just take a router (the result of createBrowserRouter() call) and set it to sagaMiddleware context and then use it from saga wherever you want.
App.tsx
const router = createBrowserRouter([
  {
    path: '/',
    element:
Home

  },
]);

sagaMiddleware.setContext({
  router,
});

export const App = () => {
  return (
    <RouterProvider router={router}/>
  );
}

saga.ts
export function* selectSmthSaga(action: ActionType<typeof selectSmthAction>) {
  const router: ReturnType<typeof createBrowserRouter> = yield getContext('router');

  router.navigate(`/path/${action.payload}/subpath`);
}

A: you can use @lagunovsky/redux-react-router instead of connected react router because it's support react router v6 ve


text:
Q: 415 unsupported media type : cloud API's I'm following this IBM cloud doc to generate a IAM token to work with the specific account to which i have access with account id doc
on postman i'm getting 415 unsupported media error

What i could be missing while validating?

A: The API for generating an IAM token is documented here in the IAM Identity Services API. You are using different (and unsupported) header and body parameters. This could cause the error.
The header should only be 'Content-Type: application/x-www-form-urlencoded'. The body should include the grant type and the API key.


text:
Q: Get error description with .htaccess/PHP I'm running an apache server, and I want the custom PHP error page to display the error number and error description. So for example, I have in my .htaccess:ErrorDocument 404 /?e=404And in my error page:
<?php
$e = $_GET['e'];
if($e === 404){
?>
Error: <?=$e?>
<?php } ?>

So it will display:
Error: 404
But I want it to show the description too, such as
Error: 404 Not Found
without having to pull from a database etc. in PHP. So is it possible to pass a parameter or something with .htaccess?

A: As far as I know, there is no magic that can translate the error code in a description for you. That doesn't mean you can't just continue on the path you already took:
ErrorDocument 404 /?e=404&desc=Not%20Found

Now the errorcode is in $_GET['e'] and the description is in $_GET['desc'].


text:
Q: C# LINQ Generic Extension Method to check if sequence is the same and return it's value I am trying to put together an extension method that will allow me to check if all values of a sequence are the same, and if so return that value, or if not return an average of that value if its an int or double or return a concatenation of that value if it is a string.
For example take the following object and a list
public class Item
{
    public int Size {get; set;}
    public string Name {get; set;}
}

var itemsTheSame = new List<Item>
{
    new Item { Size = 1, Name = "Red" },
    new Item { Size = 1, Name = "Red" },
    new Item { Size = 1, Name = "Red" }
};

I want to be able to do something like this
itemsTheSame.AllEqual(item => item.Size)); // should return 1 as an int
itemsTheSame.AllEqual(item => item.Name)); // should return "Red" as a string

My generics are not very strong, but this is what ive started off with
public static class Extensions
{
    public static int AllEqual<TSource>(this IEnumerable<TSource> list, Func<TSource, int> selector)
    {
        if (!list.Any()) return default(int);
        var first = list.First();
        return list.Skip(1).All(selector == first) ? default(int) : default(int);
    }
}

It's quite obvious to me that the return type needs to be generic aswell, so came up with this (doesent compile)
public static TReturn AllEqual<TSource, TReturn>(this IEnumerable<TSource> list, Func<TSource, TReturn> selector)
{
    if (!list.Any()) return default(TReturn);
    var first = list.First(selector);
    return list.Skip(1).All(selector == first) ? default(TReturn) : default(TReturn);
}

I am completely confused as I need to be able to pass Func<TSource, TReturn> selector to the .First() to be able to get the value itself, but .First needs a Func<TSource, bool>. I also need to be able to pass the same selector to .All as I only want to check the field specified in the selector for equality.
Is this even possible or am i better off having a set of overloaded methods, one that returns an int and the other that returns a string etc ?
Fiddle here

A: *

*Try to avoid iterating the IEnumerable multiple times. It could be too expensive, you never know.

*You need an implementation for each numeric type because of the average feature.

*Average is actually the same whether you have all the same values or not. Just use the Average extension method instead. You may want to wrap it to make the syntax the same. (Or consider to give it a different name, like AllEqualOrAverage, because it doesn't do the same.)

*The average of an int is usually a double. Decide whether you want to round it, use floor or actually return a double.

*You need Select(selector) to get the values from the items. The argument of First is a predicate, as in Where(predicate).

Proposal:
// for doubles (returning average or default if list is empty)
public static double AllEqual<TSource>(this IEnumerable<TSource> list, Func<TSource, double> selector)
{
    // use IList<T> interface to quickly check the size of the
    // list if this interface is available. Use ToArray otherwise.
    var ilist = list as IList<TSource> ?? list.ToArray();
    if (ilist.Count == 0) return 0.0;
    list.Select(selector).Average();
}

// for ints (returning average or default if list is empty)
public static double AllEqual<TSource>(this IEnumerable<TSource> list, Func<TSource, int> selector)
{
    // use IList<T> interface to quickly check the size of the
    // list if this interface is available. Use ToArray otherwise.
    var ilist = list as IList<TSource> ?? list.ToArray();
    if (ilist.Count == 0) return 0.0;
    list.Select(selector).Average();
}

// for everything else (returning unique value or default)
public static TReturn AllEqual<TSource, TReturn>(this IEnumerable<TSource> list, Func<TSource, TReturn> selector)
{
    // put 2 distinct values into an array
    var distinctItems.Select(selector).Distinct().Take(2).ToArray();
    if (distinct.Length == 1) return distinct[0];
    default(TReturn);
}

Note that this only works if you know the numeric type at compile time. If you need to return the average of a number which is only recognized at runtime (it is an object at compile time), it gets really hard.

A: First doesn't accept a selector, it accepts a predicate.  To apply a selector to the first item you need to get the first item (using its parameterless overload), and then invoke the selector on that result.
And to compare objects of an unknown type for equality you won't be able to use the ==operator.  It is bound at compile time, so it couldn't account for the specific implementation for that type, in addition to the fact that it might not have one.  You should use an IEqualityComparer<T> to compare the items for equality (you can use the default comparer if none is provided).
Also note that your implementation iterates the source enumerable up to 3 times.  That could easily be a problem if it's actually a query, and not an already materialized collection.  You're really better off just iterating the sequence explicitly, rather than using LINQ operations here, since you can't do it with just one LINQ query.


text:
Q: How many files can a windows server 2008 r2 directory safely hold? How many files can a windows server 2008 r2 directory safely hold?
I'm thinking in terms of a website that has image galleries. Say there is one directory that holds all the thumbnails and a different directory that holds the full size images. How many pairs of images can be safely stored?
Or, if there isn't a good cut-and-dry answer, should I just try it with 30,000 images?

A: If your server is using NTFS for its volume file system, you aren't limited to any number of files per directory per se, but more in that you are limited to some number of files/directories per volume.
For NTFS, size limitations are:

NTFS Size Limits
Files per volume
  4,294,967,295 (2^32 minus 1 file)

Of course, that says nothing about performance, and there are other considerations that can come into play. With 30000, you shouldn't worry. When you get into the millions, you might have to start restructuring.
edit to address scaling/performance
Technically speaking, the NTFS file system uses a global MFT that keeps track of all the files (directories are files and are mostly used for logical representation to the end user) so every time you modify the volume, that change is reflected in the MFT.
When you start having a single directory with large numbers of files, one of the recommended procedures is to disable automatic 8.3 name generation. From the technet article I linked above:

Every time you create a file with a long file name, NTFS creates a second file entry that has a similar 8.3 short file name. A file with an 8.3 short file name has a file name containing 1 to 8 characters and a file name extension containing 1 to 3 characters. The file name and file name extension are separated by a period.

So if you are constantly modifying a single directory with a large amount of files, the system has to generate a short name for it - this can lead to performance degradation if you are constantly modifying the contents of a single directory. Since you are storing images, it could be very likely a lot of the files have similar file names at the beginning, like imageblahblahblah.
For file look-up performance, even for large directories NTFS should be reasonably fast because of the underlying B-Tree implementation.
Also check out this thread: NTFS performance and large volumes of files and directories


text:
Q: If $f$ is uniformly continuous at $(a,b)$ and continous at $x=a$ how to prove it is uniformly continuous at $[a,b)$? If $f$ is uniformly continuous at $(a,b)$ and continous at $x=a$ how to prove it is uniformly continuous at $[a,b)$?
can someone give a hint plz?

A: Not so elegant option:
Let $a<c<b$;
1) $f$ is uniformly  cont. on $[a,c]$, closed, bounded interval.
2) $f$ is uniformly continuos on $[c,b)$, since $[c,b) \subset (a,b)$.
Given $\epsilon/2$.
1) There is a $\delta_1$ s.t. for $x,y \in [a,c]$
$|x-y|<\delta_1$ implies $|f(x)-f(y)|<\epsilon/2$.
2) There is a $\delta_2$ s.t. for $x,y \in [c,b)$
$|x-y|<\delta_2$ implies $|f(x)-f(y)|<\epsilon/2$.
$\delta =\min (\delta_1,\delta_2)$.
3) Let $x<c$ ,  $c<y$, and $|x-y|<\delta$.
Then
$(y-c)+(c-x) <\delta$ implies
$|f(y)-f(x)|\le $
$|f(y)-f(c)| +|f(x)-f(c)| <$
$\epsilon/2+\epsilon/2=\epsilon$.

A: Let $\varepsilon>0$. Take $\delta_1>0$ such that$$(\forall x,y\in(a,b)):\lvert x-y\rvert<\delta_1\implies\bigl\lvert f(x)-f(y)\bigr\rvert<\varepsilon$$amd take $\delta_2>0$ such that$$(\forall x\in(a,b)):\lvert x-a\rvert<\delta_2\implies\bigl\lvert f(x)-f(a)\bigr\rvert<\varepsilon.$$Now, take $\delta=\min\{\delta_1,\delta_2\}$. That will work.


text:
Q: Find the touched Area (country)on a UIImageView based on coordinates
I am Using A UIImageView with a globe image,if i touch on any region Example if i touch on any African country,I would like to fire a touch event and show that it is a particular country tapped by the user.I approached the way to get he co-ordinates on the images,Please give me any suggestions how can i get the touched positions country wise.
Thanks in advance.

A: Put the Image in UIImageView of a ViewController in Portrait mode
implement
  override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

        let  touch = touches.anyObject() as UITouch
        println(touch.locationInView(self.view))

    }

result
(155.5,164.5)


text:
Q: HP-UFT v.14.00: Object Spy freezes after clicking on "add object to repository" I am working on terminal server and have more then enough resources on my machine. From some reason every time after some object was selected and i clicked button "add object to repository" the object spy freezes for 5 minutes or more.

Did someone had that issue and knows how to make the Object spy fester?


text:
Q: Martin Isaacs's exercise 3.6 (character theory of finite groups) I'm trying to solve this exercise, can anyone help me?
Let $G$ be a p-group, and suppose $\chi\in{Irr(G)}$. Show that $\chi(1)^2$ divides $|G:Z(\chi)|$
Thanks a lot.

A: Hint: Use Corollary 2.30 and theorem 3.12.

 By Corollary 2.30, $\chi(1)^2 \leq [G:Z(\chi)]$. By Theorem 3.12, $\chi(1)$ divides $[G:Z(\chi)]$ so is a power of a prime. However $\leq$ is the same as divides for two powers of the same prime. $\square$


text:
Q: Angular Content projection with nested children StackBlitz Eample is here
I have a component where I would like the user to define there own template and then I want to pass that template to some nested children. I'm having issues getting an instance of templates in the parent component.
I have my directive here
@Directive({
  selector: '[customTemplate]',
})
export class CustomTemplate {
  public field!: string;

  constructor(public el: ElementRef) {}
}

I want to put this inside of a parent and get all instances of these directives.

  <ng-template myTemplate>

Some text here T1

  </ng-template>

  <ng-template myTemplate>

Some text here T2

  </ng-template>

<Child1>
  <Child2>I'm going to render the ng-templates of myTemplate here</Child2>
</Child1>

In my Parent Component I have this
    @Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements AfterViewInit {
  @ContentChildren(CustomTemplate)
  public templates?: QueryList<CustomTemplate>;

  ngAfterViewInit(): void {
    console.log(this.templates);
    //here how do I get the instances of CustomTemplate

  }
}

The QueryList is empty

A: I believe that content children might not be the right call. Using ViewChildren results in them being discovered. However, a few modifications need to be made.
Your selector in your directive is set as [customTemplate]. This is fine, however the selectors are case sensitive. Thus in your HTML when you use it as CustomTemplate it won't be discovered. Thus change your HTML to be either customTemplate or update your selector to have a capital C.
Secondly, in order to do anything of value with said ViewChildren, as is mentioned here (@ViewChildren Querylist Array is empty when children are rendered with *ngFor) you need to subscribe to any changes that occur in your AfterViewInit
ex:
this.templates.changes.subscribe((x) => console.log("From Change Sub: ", x));

Lastly, instead of trying to find the children using a string literal, pass in the actual class name instead as so:
@ViewChildren(CustomTemplate) instead of @ViewChildren('CustomTemplate') or @ViewChildren('customTemplate')
The latter two do not work, the first one does. Also with the first one if you ever do decide to change the name of the class it will propagate throughout the app, and anywhere it did not the typechecker will find it.
Updated stackblitz https://stackblitz.com/edit/angular-z5a8ae?file=src/app/app.component.html


text:
Q: reading excel files in access vba I am trying to read an excel file inside a access application using VBA. I have this code:
Dim xlApp As Excel.Application
Dim xlWrksht As Excel.worksheet

which I got from here:
Best way to read an Excel file into an Access database
but when I try to run it, I am getting error that user defines type is not define.
Should  I add a reference to the application?
Is there any way that  can do it without adding a reference to my application?
Edit 1
After adding reference to the code, Now I have this code:
Dim excelApp As Excel.Application
Dim workbook As Excel.workbook
Dim Worksheet As Excel.Worksheet
Set excelApp = CreateObject("Excel.application")
Set workbook = excelApp.Open(InputFileName)
Set Worksheet = workbook.Worksheets(1)

But now I am getting error on line:
Set workbook = excelApp.Open(InputFileName)

as the excelApp doesn't have any method called Open. Should I add any other reference?

A: If you know the structure of the Excel worksheet, you can link to various ranges in one worksheet, an treat each of them as a table, using queries and/or Recordsets. Last parameter in this line represents a range in the first worksheet:
DoCmd.TransferSpreadsheet acLink, acSpreadsheetTypeExcel9, myTableName, ExcelFileName, False, "f3:L10"

You remove this link as any table:
CurrentDb.TableDefs.Delete (myTableName)

A: If you do not add a reference to the objects, then Access will not have knowledge of the objects to use with variables.  An object/type is either built-in or referenced so it is usable.
You should also include Excel.Workbook, as the hierarchy is App -> Workbook -> Worksheet -> Cells.

A: You need to add a reference to your Access project, else it would not recognize it.
G.


text:
Q: What is the difference between public function and function added using prototype in Object Oriented Javascript I am trying to understand what is the difference when we write:
var Foo = function (){
 this.name = 'abc';
 this.alertName1 = function(){
  alert(this.name);
 }
}

Foo.prototype.alertName2 = function(){
  alert(this.name);
 }

Both methods will be available and are correct but when to use what is the question?

A: When you add a function to the prototype, it only exists in one place no matter how many times you instantiate Foo.
When you add a function inside the constructor, a new copy is created every time you instantiate so it's less efficient.


text:
Q: Is it possible to combine @Lock with @Modifying @Query in Spring Data JPA together with Hibernate? I have a problem when using the @Lock annotation together with @Modifying @Query and the query itself performing an update statement. My test setup looks like this:

*

*Spring Boot Starter 1.5.3.RELEASE

*Hibernate 5.2.10.Final

*Spring Data JPA 1.11.3.RELEASE

Databases tested: H2, PostgreSQL, MariaDB, Oracle
Sample entity:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Version;

@Entity
@Table(name = "\"users\"")
public class User {

    @Id
    private Long id;

    private boolean active;

    @Version
    @Column(nullable = false)
    private long version = 0L;

    // getters/setters (not shown)

}

The repository looks like this:
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

public interface UserRepository extends CrudRepository<User, Long> {

    @Modifying
    @Query("UPDATE User u SET u.active = false WHERE u.id = ?1")
    @Lock(LockModeType.OPTIMISTIC_FORCE_INCREMENT)
    void deactivate(Long id);

}

Now calling repository.deactivate(myId) results in an exception:
org.springframework.dao.InvalidDataAccessApiUsageException: Illegal attempt to set lock mode on a non-SELECT query; nested exception is java.lang.IllegalStateException: Illegal attempt to set lock mode on a non-SELECT query
    at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:381)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:246)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:488)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.mmmgroup.prork.persistence.AbstractUserRepositoryTests.deactivateUsers(AbstractUserRepositoryTests.java:230)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:114)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:57)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:66)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:109)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:147)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:129)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalStateException: Illegal attempt to set lock mode on a non-SELECT query
    at org.hibernate.query.internal.AbstractProducedQuery.setLockMode(AbstractProducedQuery.java:286)
    at org.hibernate.query.internal.AbstractProducedQuery.setLockMode(AbstractProducedQuery.java:104)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.applyLockMode(AbstractJpaQuery.java:182)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.createQuery(AbstractJpaQuery.java:190)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$ModifyingExecution.doExecute(JpaQueryExecution.java:238)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:85)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:483)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    ... 36 more
Root cause: java.lang.IllegalStateException: Illegal attempt to set lock mode on a non-SELECT query
    at org.hibernate.query.internal.AbstractProducedQuery.setLockMode(AbstractProducedQuery.java:286)
    at org.hibernate.query.internal.AbstractProducedQuery.setLockMode(AbstractProducedQuery.java:104)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.applyLockMode(AbstractJpaQuery.java:182)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.createQuery(AbstractJpaQuery.java:190)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$ModifyingExecution.doExecute(JpaQueryExecution.java:238)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:85)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:483)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.mmmgroup.prork.persistence.AbstractUserRepositoryTests.deactivateUsers(AbstractUserRepositoryTests.java:230)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:114)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:57)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:66)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:109)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:147)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:129)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:748)

The @Lock javadoc says:

Annotation used to specify the {@link LockModeType} to be used when
  executing the query. It will be evaluated when using {@link Query} on
  a query method or if you derive the query from the method name.

The official Spring Data JPA documentation says

You can also define locking for CRUD methods by redeclaring them in
  your repository interface and adding the @Lock annotation: [...]

which would include update and delete (CRUD), i.e. modifying queries, am I right?
So my question: Is it possible to combine @Lock with @Modifying @Query in Spring Data JPA together with Hibernate?

A: Locking in the context of @Lock refers to locks obtained in advance of a modifying query. @Lock accepts a javax.persistence.LockModeType, which from the JPA spec is used only by the find, lock and refresh methods of the EntityManager. find and refresh can potentially fire a SELECT query so indirectly, a @Lock is applicable only to a SELECT query.

Note: The answer of user 'manish' has been copied from the comments as is (after requesting the user to do it him/herself which did not happen for more than 2 month) and make it community wiki to have an proper answer.


text:
Q: Execute action on AsyncTask finish SITUATION
I am developing and android app for my university math class (I'm using Android Studio). What I am doing in a particular fragment is the following:

*

*Click the button "GENERATE"

*Start the AsyncTask (there is a "big" for loop inside, it goes from 0 to 5000)

*While the AsyncTask is running show a message like "Loading..."

*When the AsyncTask has finished the calculations inside that foor loop, add TableRows to a TableLayout

As you can see here, I must execute that for loop in a "separate" place (the AsyncTask) because it is going to be a problem for the UI.

PROBLEM
I have troubles when I have to code the point number 4 of the above list. You can see the entire code in this pastebin. Here I want to point out the main problem.
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        final View view = inflater.inflate(R.layout.fragment_disequazioni_generali, container, false);

        Button button = (Button) view.findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                dialog = ProgressDialog.show(view.getContext(), "", "Attendi...", false, true);

                //valori degli estremi
                EditText val_a = (EditText) view.findViewById(R.id.val_a);
                EditText val_b = (EditText) view.findViewById(R.id.val_b);
                a = Double.parseDouble(val_a.getText().toString());
                b = Double.parseDouble(val_b.getText().toString());
                derivata = getDerivative(funzione, variabili, "x");

                //setup tableview + task
                tl = (TableLayout) view.findViewById(R.id.tableLayoutTangenti);
                TextView coefficente = new TextView(view.getContext());
                EditText decimale = new EditText(view.getContext());

                mAuthTask = new TaskAsincrono();
                mAuthTask.execute((Void) null);

            }

        });

As you can see here I am creating a new object because I need to use the AsyncTask (look below):
public class TaskAsincrono  extends AsyncTask<Void, Void, Boolean> {
        @Override
        protected void onPreExecute(){
        }

        @Override
        protected void onProgressUpdate(Void[] values) {

        };

        @Override
        protected Boolean doInBackground(Void... params) {

                double x = a;
                double y = b;

                //Definizione dell'intervallo
                risultati = separaRadici(funzione, x, y, 500);

                int k = 0;

                for (int i = 0; i < (risultati.size()); i += 2) {

                    k++;
                    double a = risultati.get(i);
                    double b = risultati.get(i + 1);
                    double res = (b + a) / 2;

                    for (int j = 1; j < 10; j++) {
                        res = res - (getFunctionVal(funzione, res) / getFunctionVal(derivata, res));
                    }

                    soluzioni.add(res);

                }

            return true;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            if(dialog.isShowing()) { dialog.dismiss(); }

            //THE ISSUE IS HERE
            mostraRisultati();
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
        }
    }

When the AsyncTask finished to work ( = it has completed all the operations inside the doInBackground) I need to call mostraRisultati();.
When the AsyncTask finished to execute the for loop, the dialog disappears but the method mostraRisultati() is not working. Any idea?
Note: If you look at the pastebin you can see the entire code. While testing, I have discovered that mostraRisultati() is called when the AsyncTask has finished its process, but the for loop is not running because risultati.size() is zero. What am I missing?


text:
Q: Python XML API request on Linux cmd returns output with request's detail. Is there a way to hide or not receive it? Here is the example :
query_state = "curl -k --location -g --request GET 'https://hostname/api/?type=op&cmd=<show><state></state></show>&key=API-KEY'"
get_state = os.popen(query_state).read()

soup = BeautifulSoup(get_state, 'lxml')
state = soup.find('state').string
print(state)

Here is output:
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  4538  100  4538    0     0  27840      0 --:--:-- --:--:-- --:--:-- 27840

active

I need only 'active' which is fine, but to reject request view?
I tried with:
get_state = os.system(query_state)

but output cannot be assigned to a variable.

A: You can hide the verbose output with the curl --silent flag.
https://curl.se/docs/manpage.html


text:
Q: Form validation in Flask This is my flask form for login form. It does not like this validation that requires both university form field as well as email form field - the error that I keep on getting is
TypeError: validate_university() missing 1 required positional argument: 'email'
class RegistrationForm(FlaskForm):
     username = StringField('Username', validators=[DataRequired()])
     password = PasswordField('Password', validators=[DataRequired()])
     password2 = PasswordField(('Repeat Password'), validators=[DataRequired(),EqualTo('password')])
     university = SelectField("What University do you go to?",choices=[("soton","University of Southampton"),("solent","Solent
 Southampton University")])
     email=StringField("What is your university email?",validators=[DataRequired(),Email()])
     submitpassword = SubmitField('Submit your password choice')

     def validate_username(self, username):
         user = User.query.filter_by(username=username.data).first()
         if user is not None:
             raise ValidationError(('Please use a different username.'))

     def validate_university(self,university,email):
         uni = University.query.filter_by(code=university.data).first()
         if not email.data.endswith(uni.emailend):
             raise ValidationError(("Please enter correct university e-mail for the university you attend."))

         user = User.query.filter_by(email=email.data).first()
         if user is not None:
             raise ValidationError(('This e-mail is already in use. Please use a different email address.'))

This is the corresponding route python function :
 @bp.route('/reg1', methods=['GET', 'POST'])
 def reg1():
     if current_user.is_authenticated:
         return redirect(url_for('main.index'))
     form = RegistrationForm()
     if form.validate_on_submit():
         user = User(email=form.email.data,username=form.username.data)
         user.set_password(form.password.data)
         db.session.add(user)
         db.session.commit()
         flash('Congratulations, you are now a registered user!')
         return redirect(url_for('auth.reg1'))
     return render_template('auth/test.html', title='Register',
                            form=form,lenform=lenform,postcodes=postcodes)

How can i fix it? Why does it not allow me two positional arguments for university validation form?
Thanks

A: Cuastom validation methods have to be defined with the "form, field" signature, meaning you can not have a validator with the (self,university,email) parameters.
You can, however, access other fields of the form in your validator through the form parameter:
 def validate_university(form, university):  # <- correct signature
     uni = University.query.filter_by(code=university.data).first()
     email = form.email  # <- access the email field like so
     ....


text:
Q: How Can I Index and Search with Elasticsearch IndexResponse response = client.prepareIndex("face", "book","1")
                .setSource(jsonBuilder()
                        .startObject()
                        .field("name", "kimchy")
                        .field("postDate", "2010-03-01")
                        .field("message", "trying out Elastic Search")
                        .endObject()
                )
                .execute()
                .actionGet();
String index = response.getIndex(); // index : "face"

SearchResponse r = client.prepareSearch("face")
    .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
    .setQuery(QueryBuilders.termQuery("name","kimchy"))
    .setFrom(0).setSize(60).setExplain(true)
    .execute()
    .actionGet();
      System.out.println(r);
      SearchHit[] hits = r.getHits().getHits();
      System.out.println(hits.length); // 0 Hits
      for (SearchHit searchHit : hits) {
      // no hits no data
      }

How can I fix this , where is the problem here ? My each attempts gives 0 hits.I tried everything but i could not fix.I will be happy if someone help me to fix this code.If I write prepareIndex("twitter", "tweet","1") and client.prepareIndex("twitter", "tweet","1") it gives me some results but i think this is default result.I want to search specific word which i want.

A: The problem is that search works in near real-time, which means that a refresh needs to happen after you indexed a document in order for it to be available for search.
A refresh automatically happens every second by default, but in your test you need to either call refresh manually to make sure the document is found, or switch to using the get api, which works in real-time, to make sure the document is present, getting it back by id.
In case you add refresh, you can either call the refresh api or add the refresh flag to the index operation, so that a refresh will happen after the document is indexed. Just remember that this is good practice while testing, but in production your code shouldn't call refresh manually, just let the automatic refresh kick in every second.

A: Try adding
.setRefresh(true)

To your client.prepareIndex call


text:
Q: Google Analytics API Cost Data Upload stuck I followed Management API - Daily Upload Developer Guide and created installed java application to upload Cost Data to Google Analytics. But It somehow doesn't work. I have Analytics service created authorized with https://www.googleapis.com/auth/analytics scope and now I want to upload some Cost Data.
I did it according to mentioned Guide like this.
File file = new File("data.csv");
InputStreamContent mediaContent = new InputStreamContent('application/octet-stream', new FileInputStream(file));
mediaContent.setLength(file.length());

// You can ignore following three lines... those are there to make sure Analytics service works.
Accounts accounts = analytics.management().accounts().list().execute();
Account account = accounts.getItems().get(0);
System.out.println("Account ID is: " + account.getId());

Analytics.Management management = analytics.management();
Analytics.Management.DailyUploads dailyUploads = management.dailyUploads();

// Here it gets stuck!
Analytics.Management.DailyUploads.Upload upload = dailyUploads.upload("AccountID",
  "PropertyID", "CustomDataSourceID", "yyyy-MM-dd", 1, "cost", mediaContent);

upload.setReset(true);
DailyUploadAppend append = upload.execute();

I added some lines to retrieve Accounts and print AccountID of the first Account... just to be sure that Analytics service works.
And it does. I am able to get AccountID but I am not able to upload my Cost Data. I don't know what is wrong... but it gets stuck when it tries to get the Upload object.
It doesn't throw Exception. It just holds there and does nothing. Is there something I am missing? I will be grateful for any help.

A: Turns out that I downloaded java client library 1.13.2. from here
Java Client Library doesn't contain Management API google-api-services-analytics-v3 So I downloaded the newest from here it was v3-rev20-1.8.0-beta
I found both in Developer Guide client libraries link
But today I found rev26-1.13.2-beta here and used it in my solution. Now Everything works, so it was just an incompatibility issue caused by misleading links in Developer Guide.
EDIT
For people struggling with this problem in the future. Be sure your libraries are compatible. As you can see I was able to GET AccountID of the first Account so I thought everything was OK, but it wasn't. There are many missleading links in Google Guides and what I found I reported via Google Groups. For me there was a hint. I had google-api-java-client-1.13.2-beta and google-api-services-analytics-v3-rev20-1.8.0-beta.
But problem is there was no sign of newer version... I downloaded what I thought was the newest from their mercurial repository. And still there was a newer version accessible only from one link somewhere deep in developers guide. I hope it will be better in the future.


text:
Q: Android call php in for loop I have a ListView with more than 40 items and I want to save their details on MySQL. All works well for the first 4-5 items then the loop stops without any error.
String student,obtained_value,max_value;

for (int i=0;i<listStudent.getChildCount();i++) {
    View view=listStudent.getChildAt(i);
    studentIdTxt=(TextView) view.findViewById(R.id.student_id_ls);
    obtainedTxt=(EditText) view.findViewById(R.id.obtained);
    maxTxt=(TextView) view.findViewById(R.id.max);
    student=studentIdTxt.getText().toString();
    obtained_value=obtainedTxt.getText().toString();
    max_value=maxTxt.getText().toString();
    //updating the new mark list array
    /*HashMap<String,String>studentMark=new HashMap<String,String>();
    studentMark.put(TAG_STUDENT_ID,student);
    studentMark.put(TAG_MARKS_OBTAINED,obtained_value);
    studentMark.put(TAG_MARKS_MAX, max_value);*/
    //studentMarksList.add(studentMark);
    //transform studentMarksList to json
    //String studentList=gson.toJson(studentMarksList);

    String URL_CHECK=domain+"/app/caller.php?action=save_marks&work_id="+workId+"&student="+student+"&obtained="+obtained_value+"&max="+max_value+"&course="+course+"&staff="+staff;

    String response=caller.makeServiceCall(URL_CHECK,serviceHandler.POST);

    boolean result=false;
    Log.d("Response: ", "> " + response);

    if (response != null) {
        try {
            JSONObject jsonObj = new JSONObject(response);

            // Getting JSON Array node
            ServerReply = jsonObj.getJSONArray(TAG_CHECK_RESULT);
            JSONObject c=ServerReply.getJSONObject(0);
            String error_txt= c.getString(TAG_ERROR_TXT);
            String error_code=c.getString(TAG_ERROR_CODE);
            String message=c.getString(TAG_MESSAGE);
            if(error_txt.equals("success")){
                result=true;
            }else{
                result=false;
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    } else {
        Log.e("ServiceHandler", "Couldn't get any data from the url");
    }
}

The commented lines were used when I tried to put them in an array then send them all at once as JSON, but it didn't worked.
How can I save all the items from the ListView without the loop stopping?

A: Network I/O is slow. You need to move slow I/O operation out of main thread (UI thread). You can try AsyncTask. It helps if you can show your logcat output.

A: Try This:
Put your Listview data in string array
String[] item = new String[user_list.size()];
int index = 0;

            for (int i = 0; i < user_list.size(); i++) {
              item[index] = user_list.get(i).getId();
                    index++;
                 }

Convert your array into single string param by this:
String user_id = Arrays.toString(item);

Then put this as a param.


text:
Q: How to fetch data in mysql with next and previous I have a database which has more than 5,000 records, I would like to fetch 50 rows and then fetch the next 50 when user clicks next and the opposite when user click previous.
Table name: events
my trial was to
select * from events where entred_by = '$id' limit $limit, 50

but the problem is I am failing to calculate the next rows and previous rows.

edit

        $start = '0';
        $PAGE_P = $_GET['p'];
        $PAGE_N = $_GET['n'];
        if(!numeric($PAGE_N)){
            $PAGE_N = 50;
            $PAGE_P = 0;
            $start = '0';
        }else{
            if(isset($_GET['n'])){
                $PAGE_N = $PAGE_N + 50;
                $PAGE_P = $PAGE_N - 50;
                $start = $PAGE_N;
            }else{
                $PAGE_N = $PAGE_P + 50;
                $PAGE_P = $PAGE_N - 50;
                $start = $PAGE_P;
            }
        }
        $this->query = SQL::get("
            SELECT * FROM event
            INNER JOIN user
            ON user.user_id = event.entered_by
            ORDER BY event_id ASC LIMIT $start,50
        ");

I have made an edit, with the edit I am able to use next button, which works, but when I press previous it is going back to row 1.

A: SELECT * FROM events WHERE entred_by = '$id' ORDER BY id LIMIT $start, $limit

Set the $start value (row number to start on) and $limit (50).
You need to use the LIMIT keyword and probably ORDER BY too.
Update for edit:
Okay, ignoring the validation, it should be something like this:
$this->query = SQL::get("
            SELECT * FROM event
            INNER JOIN user
            ON user.user_id = event.entered_by
            ORDER BY event_id ASC
            LIMIT $start_row, $number_of_rows
        ");


text:
Q: Exact match on value in object/array I have a problem with counting the number of occurences of a string from an array in a field in an object.
The XML below has 3 'Level3' items with 1 'TextLine' field each.
I need to count how many times each text in the variable 'texts' occurs in the payload.
fun getVasCount(texts) =
    sizeOf (Level1.*Level2.*Level3.*TextLine filter (texts contains $))

So instead of getting the count:2 I got the count:3 because 'a text' is a substring of 'This is a text'
var texts = {
    "This is a text": "",
    "This is another text": ""
}

<?xml version="1.0" encoding="UTF-8"?>
<ns:Level1
    xmlns:ns="aaaa:bbbb:cccc:dddd">
    <Level2>
        <Level3>
            <TextLine>This is a text</TextLine>
        </Level3>
        <Level3>
            <TextLine>This is a text</TextLine>
        </Level3>
        <Level3>
            <TextLine>a text</TextLine>
        </Level3>
    </Level2>
</ns:Level1>

A: A way to do it is to count occurrences for each different texts grouping them by value and counting how many elements are in each group.
And then modify your texts object with the counts.
%dw 2.0
output application/json
var texts = {
    "This is a text": "",
    "This is another text": ""
}
var textLines = payload.Level1.*Level2.*Level3.*TextLine default []
var grouped = textLines
    groupBy $
    mapObject (groupValues, text) -> {(text): sizeOf(groupValues)}
---
texts mapObject {($$): grouped[$$] default 0}

The result would be:
{
  "This is a text": 2,
  "This is another text": 0
}

Note: Not really modifying texts, since objects are immutable, it's creating a new one.


text:
Q: Алгоритм Хаусхолдера (метод отображений) не работает Задача - решить СЛАУ приведя матрицу А к верхне-треугольному виду используя алгоритм Хаусхолдера (метод отображений). Так вот матрица не становится треугольной. Не могу найти ошибку. Все формулы взяты из методички.
def HH(A, b):
     n = A.shape[0]
     for j in range(n):
        H = np.eye(n)
        a = A[j:, j].copy()
        r = np.linalg.norm(a, ord = 2)
        w = np.array([])
        if r == 0 or np.array_equal(a[a==0], a[1:]):
            w = 0
        elif r != 0 and a[0] == 0:
            a[0] -=  r
            w = a/np.linalg.norm(a, ord = 2)
        else:
            a[0] += r*np.sign(a[0])
            w = a/np.linalg.norm(a, ord = 2)
        H[j:, j:] -= 2*np.outer(w, w)
        A = np.dot(H, A)
        b = np.dot(H, b)`


text:
Q: what's wrong in this code (array in function output nothing)? why the array "$access_level" in protect_page function output nothing ?
I don't know what's wrong in this code to prevent array "access_level" from output ..
what I need to edit to fix that issue
session_start();
include 'C:\xampp\htdocs\database\agtdatabase\agt_site\connection\connect.php';
if (isset($_SESSION['sessionloginid']))// point to id of user logged in
    {
    $query =
        "SELECT *
        FROM privilege
        where login_id='" . $_SESSION['sessionloginid'] . "'  ";

    $access_level = array();
    $result = mysqli_query($link, $query) or die('');
    while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
        {

        $_SESSION['sessionloginid'] = $row['login_id'];
        $_SESSION['sessionaccess'] = $row['AccessLevel']; //output
        $access_level[] = $_SESSION['sessionaccess'];
        print_r ( $access_level)//output Array([0]=>1)Array([0]=>1[1]=>2)
        }

    function protect_page()
        {

        $access_level = array();
        $access_level[] = $_SESSION['sessionaccess'];
        if (in_array(1, $access_level))
            {

//  header ('location:http://localhost/database/agtdatabase/agt_site/agtSite/agt2.php');

            print_r($access_level); //output nothing
            exit();
            }
        }

    }//end of parent if

protect_page();
ob_end_flush();

A: Assuming what you wrote in the comments is what you see, you might want to note that
$access_level[]=$_SESSION['sessionaccess'];

adds the entire $_SESSION['sessionaccess'] array as the first element of $access_level, so $access_level is
Array([0]=>(Array([0]=>1[1]=>2))

hence it doesn't contain the value 1, hence in_array(1, $access_level ) is false, so the redirection/print_r never happen.
Andrei


text:
Q: Combine multiple streamed JSON objects into a single JSON object - remove first returned object I've seen the answers to similar questions - but they do not solve the issue I'm having.  So here goes..
I have a response from a MailChimp EXPORT API that looks like this:
["Email Address","First Name","Last Name","Source","Open","MEMBER_RATING","OPTIN_TIME","OPTIN_IP","CONFIRM_TIME","CONFIRM_IP","LATITUDE","LONGITUDE","GMTOFF","DSTOFF","TIMEZONE","CC","REGION","LAST_CHANGED","LEID","EUID","NOTES"]
["email1@somewhere.com","","","BORN","",2,"",null,"2015-05-07 15:25:48",null,null,null,null,null,null,null,null,"2015-05-07 15:25:48","74554133","ar5jiewpkc",null]
["email2@somwhere.com","","","BORN","",2,"",null,"2015-05-07 15:25:48",null,null,null,null,null,null,null,null,"2015-05-07 15:25:48","74554137","ar5jiewpkc",null]

What I need to do is two things:

*

*Remove the first stream object (containing "Email Address" .. etc)

*Combine the rest of the objects into a single JSON response to pass to a script as if it were a single regular JSON response.

This is a JSON "Stream" that I need to turn into a regular JSON response.
I've successfully turned them all into arrays, but when I try to json_encode the array of arrays, I get back escaped data that is not a true JSON object.
Any help is appreciated!


text:
Q: Why are different answers obtained for a regression F-test when using SSE and R2 formulas? I cannot understand what I'm doing wrong with an F-test for the regression - I get completely different answers using SSE and R2 formulas.
Unrestricted model:

Restricted model:

1 restriction is imposed, so q=1 in both cases.
Calculation with SSE:
$F=\frac{SSE_r-SSE_u}{SSE_U}*\frac{N-K}1=\frac{2.252-2.142}{2.142}*48=2.465$, same result given by Stata F-test.
Calculation with R2: $F=\frac{Ru^2-Rr^2}{1-Ru^2}*48$=1216.94
What am I doing wrong?!

A: As mark999 notes, these two models can't be compared via an F-test because they aren't nested--they are two completely different models, as is clear from the fact that the total sums of squares are wildly different in the two models.
You can only use an F-test to compare two linear models when the models are of the form
$$y = \beta_0 + \beta_1 x_1 + \beta_2 x2 + \epsilon$$
and
$$y = \beta_0 + \beta_1 x_1 + \epsilon,$$
i.e., where they have the same response variable and the predictors in the reduced model are a strict subset of the predictors in the full model.


text:
Q: Java Function Return to React-Native I'm developing an application with an integration Smart-POS. My application is in React-Native and the card reading or printing options are created through Java functions.
In other words, I'm calling a function in React-Native that is requesting a function in a Java file that communicates with the device and gives me a return.
Problem: I'm not getting any return after executing the functions in Java.
Here are code details:
React-Native Code:
import Apos from '../../../Apos';
const verifyService = async () => {
try {
  let info = {
    type: 1,
    value: 380,
    payment: 1,
    codvenda: "1",
  };
  const services = await Apos.startPayment(info);
  console.log('retorno: ',services);
} catch (error) {
  console.log('erro:', error);
}};

After executing this function, I call the Apos.js file that contains this information:
import { NativeModules } from 'react-native';
module.exports = NativeModules.APOSHardwareCommunication;

This file then calls a .java file with the function I'm requesting:
@ReactMethod
public String startPayment(ReadableMap data) {
    // Define os dados do pagamento
    PlugPagPaymentData paymentData =
    new PlugPagPaymentData(
    data.getInt("type"),
    data.getInt("value"),
    data.getInt("payment"),
    1,
    data.getString("codvenda"));
    // Cria a identificação do aplicativo
    PlugPagAppIdentification appIdentification =
    new PlugPagAppIdentification("MeuApp", "1.0.7");

    PlugPag plugPag = new PlugPag(reactContext, appIdentification);

    PlugPagInitializationResult initResult = plugPag.initializeAndActivatePinpad(new PlugPagActivationData("1170496755"));

    PlugPagTransactionResult result = plugPag.doPayment(paymentData);

    return String.valueOf(result);
}

In this return, through adb logcat I can see if putting one System.out.println(result); is returning all the transaction data to the console, but it goes back to React Native with return undefined.
This is an example of a return:
PlugPagTransactionResult(message=ERRO NO CARTAO - NAO TENTE NOVAMENTE, errorCode=R 30, transactionCode=null, transactionId=null, date=null, time=null, hostNsu=null, cardBrand=null, bin=null, holder=null, userReference=null, terminalSerialNumber=null, amount=null, availableBalance=null, cardApplication=null, cardCryptogram=null, label=null, holderName=null, extendedHolderName=null, result=-1004)

For details, I'm integrating PagSeguro's Moderninha API.
Has anyone been through this situation?

A: You just need to change your function from String to void and send the response as a promise, like this:
@ReactMethod
public void startPayment(final Promise promise, ReadableMap data) {
  // ...
  promise.resolve(String.valueOf(result));
  return;
}


text:
Q: Interpretations of this residual value scatterplot of LinearRegression GridSearch CV model I am very new to machine learning and did a first mini project predicting house price using GridSearchCV, elastic net model.
Then I plotted out the residual value (Y_Predict - Y_Train) but I want to know whether the graph tells my model is good or bad? How do I translate it into valuable write-up? Or is there any other graph that I can use to tell more stories? I am sort of clueness about what else I can do based on this model, as this is my first model and I dont really know about the options so far. Thank you in advance!
P.S. The MSE I got is 14195, RMSE is 20558, mean value of the dataset label "SalePrice" is 180815.

A: Okay,
The thing about residual plot is, If you find any patterns forming, It indicates a problem in your model. There is no specific pattern forming in the residual plot given.
Moreover a Mean Absolute error of 119 is not at all bad for this data set. That means on an average, Your prediction are off by 119. This may not be enough but this is a good indicator to show that you are proceeding in the right direction.
You can do on more thing, If this is a 2 feature data-set, You can plot out the Test values actual prediction graph vs the true test values and see the smoothness of the line its fitting


text:
Q: How can I get different action bar names? I can change the name in the action bar with the manifest, but then the action bar title of every activity will change. How can I change only one?

A: Each <activity> can have an android:label attribute, with the display name of that individual activity. If an <activity> element lacks that attribute, Android uses the android:label on <application>. So, add android:label attributes to all of your activities, with each containing your desired display name of the activity:
<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name">
    <activity
        android:name="MainActivity"
        android:label="@string/main_activity_display_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
    <activity
        android:name="OtherActivity"
        android:label="@string/other_activity_display_name"/>
</application>

A: In Your activity code use:
setTitle("title");


text:
Q: Is it possible to mix solid and dashed cell border styles with Prawn? I'm building a site with Ruby on Rails 3.1 where I also need to have PDF versions of certain data. For this I use Prawn (master) with the Prawnto gem. Works really well. However, there is just this one thing that I cannot see how to get done.
The PDF contains tabular data where I would like to change the cell border styles differently to better visualize certain parts. At the moment I have rows that can be single or multiple grouped together. The single line or group should have a solid border around it to show that this is a group.
 -----------------------------------------------------------------
| Row 1                                                           |
 -----------------------------------------------------------------
 -----------------------------------------------------------------
| Row 1                                                           |
|                                                                 |
| Row 2                                                           |
 -----------------------------------------------------------------

Now what I'd like is to have a dashed/dotted line between row 1 and row 2 in the second group. I'd also need to in certain cases have vertical (left/right) dashed/dotted borders in cells.
 -----------------------------------------------------------------
| Row 1                                                           |
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -|
| Row 2                                                           |
 -----------------------------------------------------------------

I've been trawling the web for examples, but no luck at all. How can this be done? The only thing I can do is to dash all borders in the table, but this is not what I want.
pdf.dash 4, :space => 3
pdf.table data

I would like to be able to set the border styles individually for each cell, but also in a way where a cell can have different styles for different borders. I.e. top is solid and bottom is dashed.
Any suggestions or help how I can achieve this? Would a text box or bounding box help instead of using a table?
Thanks in advance!

A: No, this is not possible currently.
I have made a fork of prawn and added the necessary code that allows to mix solid, dashed and dotted cell borders in a table.
You can find the fork here.
Example usage when creating a table cell:
:border_lines => [:solid, :dotted, :dashed, :dashed]


text:
Q: margin-top not working properly inside inline-block form I have a form that has a input text type inside, I am placing it right in front of a select object with the following code, but it is not exactly aligned with the select object.

When I try to introduce margin-top in the css as shown below, it moves both the select object and the text box below:
form {
    display: inline-block;
}

.textBox
{
margin-top:50px;
}

Please guide me about this issue.

A: Get rid of the margin for .textBox and try this:
form{display:block;}
form input{
    display: inline-block; vertical-align:middle;
}

WARNING: this will align ALL your input elements, so you may need to add more declarations if you have more elements and you need it so. If it's just these 2 elements, then you'll be OK

A: Try putting the margin-top:.5em; in the style of the line:
 <input class="textBox" type="text" value="A random value" style="width:222px;     height:36px; font-size:24px; padding-left:11px;padding-top:2px;color:#666666; margin-top:.5em;">


text:
Q: Nuget, portable library and WinRT appx: Payload contains two or more files with the same destination path
*

*Create new Windows 8 application App1

*Add ClassLibrary1 Windows 8 class library project to solution

*Add PortableClassLibrary1 portable class library targeting Windows 8 and Windows Phone 7.5 to a solution

*Reference HttpClient nuget package in ClassLibrary1

*Reference HttpClient nuget package in PortableClassLibrary1

*Reference both ClassLibrary1 and PortableClassLibrary1

*Compile solution

You get an error at .appx package stage
Payload contains two or more files with the same destination path 'System.Net.Http.Primitives.dll'.
Source files:
\Projects\App1\PortableClassLibrary1\bin\Debug\System.Net.Http.Primitives.dll
\Projects\App1\packages\Microsoft.Net.Http.2.2.13\lib\win8\System.Net.Http.Primitives.dll

Please note the same error is reproduced if you reference any nuget package featuring both win8 and portable blends of assemblies.
What is expected:
Most specific version of a library (win8 one) is packaged into .appx and portable version is ignored
Any ideas on how to cheat appx packager and build this kind of Windows 8 projects?

A: It looks like the solution described here works: http://cyanbyfuchsia.wordpress.com/2013/05/03/payload-contains-two-or-more-files-with-the-same-destination-path/
Basically, you must set "Copy local" to false in the WinRT project that is referenced from the main app.

A: In addition to this, you should be getting warnings similar to:

All projects referencing ClassLibrary1.csproj must install nuget
  package Microsoft.Bcl.Build. For more information, see
  http://go.microsoft.com/fwlink/?LinkID=317569.

This is indicating a problem. Basically, the short of it, you should be installing HttpClient.Compression into all projects. MSBuild/AppX packaging doesn't know which binary to deploy between the portable library and store library project (they have different APIs & versions). Installing the package into the application, tells it.

A: I had such issue too. It was because I shared one of my solution between projects. I had to rename the solution, because the name was all the same like one of the projects. After renaming I had this problem.
I fixed it by: right click on solution I renamed and used both projects, then properties, then use same name in the assembly name like solution name.


text:
Q: Mockito UnfinishedStubbingException in LamdaFunction I am trying to mock
this.restTemplate =
restTemplateBuilder
    .messageConverters(converter)
    .requestFactory(() -> new HttpComponentsClientHttpRequestFactory(httpClient))
    .build();

I am using following code
doReturn(restTemplateBuilder).when(restTemplateBuilder).messageConverters(any(MappingJackson2HttpMessageConverter.class);
doReturn(restTemplateBuilder).when(restTemplateBuilder).requestFactory(lambdaCaptor.capture());
doReturn(restTemplate).when(restTemplateBuilder).build();

The requestFactory part is giving error
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:

A: The error

ERROR - org.mockito.exceptions.misusing.UnfinishedStubbingException: Unfinished stubbing detected here

happens because some of these cases:

*

*missing thenReturn()

*you are trying to stub a final method, you naughty developer!

*you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed

I think that your example is close to the third item. You cannot use captor object -> lambdaCaptor.capture() inside a Mockito.when().
Basically, you need to find a way to mock HttpComponentsClientHttpRequestFactory. There might be multiple ways to do it. I would start looking at how to mock the interface that it implements: ClientHttpRequestFactory. Here on the official source code there are some examples. This answer also looks very close to what you need.


text:
Q: Passing by refence fails when using the function call within a cout statement The usual concept of passing a variable by reference to a function is that you want to use that exact variable and not its copy, which is fine. But suppose you have this code:
#include <iostream>
using namespace std;

    int dev(int &a, int b)
    {
        a = 5 + b;
        return b;
    }
    int main()
    {
        int a = 0;
        int b;
        cin >> a >> b;
        cout << dev(a, b) << " "<< a;
        return 0;
    }

for inputs a = 5, b = 10 I am expecting to output 10 15, but I get 10 5.
Now the problem goes away if instead of
    cout << dev(a, b) << " "<< a;

I write
int res = dev(a,b);
cout << res << " " << a;

I was wondering why it would be so?
Edit: spelling


text:
Q: R Keras - super simple LSTM example with fit error I'm trying to build a toy model to demonstrate how LSTMs can predict the next few iteration of a sequence. My code runs without any errors until the last line.
# Simulating dummy data
seq <- data.frame(x_train = (seq(0,8, 1)/10), y_train = (seq(0,8, 1)/10))
seq$x_train <- seq$x_train + 0.1

# Reshaping
x_train <- array_reshape(seq$x_train, dim = c(9,1,1))
y_train <- array_reshape(seq$y_train, dim = c(9,1))

# Checking dimensions
dim(x_train); dim(y_train)

# Building the model
m <- keras_model_sequential()
m %>%
  layer_lstm(units = 10, input_shape =c(9,1), batch_size = 9, return_sequences = T, stateful = T) %>%
  layer_dense(units = 1)

summary(m)

# Compiling
m %>% compile(loss = "mse", optimizer = "adam")

This is where the issue arises -
for (i in 1:9) {
  m %>% fit(object = x_train, y_train, batch_size = 1, shuffle = FALSE)
  m %>% reset_states()
}

I get the following error, and I'm not sure why:
Error: $ operator is invalid for atomic vectors
Anyone know what I'm doing wrong?


text:
Q: Why can't AKS pull the image from ACR? I have an AKS cluster and an ACR registry in Azure. The cluster contains several Windows nodes where a WindowsServerCore based service is deployed. The image is in ACR, but for some reason I can't get it to pull the image, I always get the imagePullBackOff error.
I have tried all methods, attach the ACR in AKS, through a Secret (both using ACR admin and through a new Service Entity), but there is no way, everything fails. The strange thing is that when I do a kubectl describe pod it doesn't return me anything concrete, only the imagepull error, nothing else. It does not indicate authentication error...
Events:
  Type    Reason   Age                    From     Message
  ----    ------   ----                   ----     -------
  Normal  BackOff  85s (x1341 over 5h6m)  kubelet  Back-off pulling image "myacr.azurecr.io/so99:860"

Any idea what could be happening?

A: you need to integrate AKS with ACR via AcrPull permission.
If you have existing cluster use this command:
az aks update -n myAKSCluster -g myResourceGroup --attach-acr <acr-name>

To create new cluster with integration use:
az aks create -n myAKSCluster -g myResourceGroup --generate-ssh-keys --attach-acr <acr-name>


text:
Q: How to redirect back to client app when linking to keycloak admin console? I am currently builing a VueJS SPA which is secured by keycloak.
There is the convenient function keycloak.accountManagement() in the keycloak-js to switch between a user's account information in the keycloak's Account Service and back to the client application. But for the admin console I haven't found something similar.
What I do is using an Anchor
Verwaltung

which works fine in one direction. But from there is no way back to my application. Once the console is entered, the history of my browser seems corrupted, because the back button doesn't bring me back to my application.
Is there any programmatic way to force a redirect back?


text: Q: Emu8086 shorten compile time I've written a 1100 lines Assembly code with Macros in emu8086 (without Macros it would be around 2700 lines) and compiling this program takes arround 2 minutes. It gives me 8 passes. I'd like to ask, whether it is possible to cut down on compile time?


text:
Q: Does Nexus 3 support Maven? This looks like a simple question but I haven't been able to find the answer. I'm looking to try out Nexus and in the download page I see:
Nexus Repository Manager OSS 3.x
Manage these formats:
Docker NuGet npm Bower PyPI Ruby Gems

Nexus Repository Manager OSS 2.x
Manage these formats:
Maven P2 OBR Yum

Does it mean that Nexus 3 doesn't support Maven?

A: In my company we are using Nexus 3 as repository for jars with maven, and everything is fine with that.
Notice that in Nexus 3 you can't upload a third party jars from the UI like Nexus 2. It's the only disadvantage that I found.

A: Nexus Repository 3 does in fact support Maven (2) as a format. The wording here was more so historically such that people wandering in might be better served using Nexus Repository 2 for Maven, since it has quite a lot of features that were built specifically with Maven in mind. However the gap has been closed fairly significantly, and at this point I think you'd be well served to use Nexus Repository 3. I'll see if I can get the download page updated to reflect that.


text:
Q: Perfectly flat surface Looking at microscopic images of work tops I noticed that none are perfectly flat.
Is it possible to actually create a perfectly flat surface?

A: It depends on what you mean by "surface" I suppose. If you mean general work surface then I don't know. I do know of at least one purportedly "perfectly flat" material though, due to the geometric arrangement of it's atoms:
https://en.wikipedia.org/wiki/Mica