text:
Q: Unable to return value to caller function scala I am trying to call one of the utility functions, but unable to return value to the caller, but somehow I am not able to return the response to the caller; i.e the main function. What could be the issue?
I tried reassigning the response to a local variable and returning that; but did not work
// main function
def main(args: Array[String]): Unit = {
  val res = fetchFromDruid()
  // res comes as null here
}

def fetchFromDruid(): GroupByResponse {
  // creating an execution context

  // creating a local druid client

  // constructing a group by query

  // executing the query
  client(query).onComplete {
    //this will be executed if data is fetched successfully
    case Success(response) =>
      return response

    //this will be executed if there is an exception
    case Failure(ex) =>
      ex.printStackTrace()
      return null
  }
}

Expected: The main method (caller) should get the response
Actual: The caller does not get the response after the callback returns

A: Consider the following:
def f() :Unit = return 3

val x = f()  //x: Unit = ()

You can't return a value from a method that doesn't return a value, which is what your code is trying to do.
Look at the type signature of onComplete().
abstract def onComplete(f: (Try[T]) ⇒ U)(executor: ExecutionContext): Unit

onComplete() appends new code to the end of a Future executing on a separate thread. The code will, eventually, be executed but onComplete() returns Unit (no useful value) to the caller right away, so your return statements are meaningless. (And poor Scala style. Don't use return. It will mislead you.)


text:
Q: Using enum with a switch case String for my assignment I've made changes to the code and was able to successfully I hope use the switch case with a String. Now I just need help declaring two variables for the string getDirection. I need it to be declared as "Right" and "Left"
String quit= "exit";
  String choice;
  String getDirection= "Right";//I need it to be declared as both left and right

  quit.equalsIgnoreCase("exit");

do
{
  System.out.println("would you like the bug to move or turn around?");
  System.out.println();
  System.out.println("Or enter 'exit' to quit");
  choice= scan.nextLine();

  option options=option.MOVE;

  switch(options)
  {
      case MOVE:
          b.move();
          if (getDirection.equals("Right"))
              System.out.println("The bug moved 1 unit towards " + b.getDirection("Right ") + " and is now at position " + b.getPosition());
              else if (getDirection.equals("Left"))
              System.out.println("The bug moved 1 unit towards " + b.getDirection("Left ") + " and is now at position " + b.getPosition());

A:   if (b.getDirection.equals("Right"))//this getDirection is showing up as an error

That's because there's no member variable called getDirection in class Bug.
You have defined a local variable called getDirection, which is unrelated to class Bug.
Probably you intended a method call, b.getDirection(), by analogy with your similar calls in the same section of code.
Incidentally, IMO variables should have noun phrases for names, not verb phrases.  So, method getDirection() is well-named, variable getDirection is not.

redpajama_set_name: RedPajamaStackExchange


text:
Q: React display logout button I am using react and session storage to store user data. The reason to use session storage is because on window close, I want the data to be deleted.
The first step I take is to call the API and sent the credentials.
const handleLoginForm = async e => {
    e.preventDefault();
    try {
      const user = await axios.post('https://API-web.herokuapp.com/api/login', {email, password});
      if (user.request.status === 200 && user.request.statusText === 'OK') {
       // Stringfy the object and create a
        sessionStorage.setItem('user', JSON.stringify(user.data[0]));
        navigate('/dashboard');
      }
    }
    // Catch error block
    catch (error) {
      if (error.response.data === 'Invalid credentials' && error.response.status === 404)
        return setError(error.response.data);
      else
        return setError('Something went wrong. Please try again or contact us.');
    }
  }

The second step is to create the header and use conditional rendering. If the user is found in the session storage, than display the logout button.
However this is not working unless I refresh the page. Same on login and also on logout.
const Header = () => {

  const [isDesktop , setIsDesktop] = useState(true);
  const [user, setuser] = useState(false);
  const navigate = useNavigate();

  const handleHeader = () => {
    setIsDesktop(!isDesktop);
  };

  const getUser = async () => {
    const userObj = await sessionStorage.getItem('user');
    setuser(userObj);
  }

  useEffect(() => {
    // Get user from sessionstorage
    getUser();
  }, []);

  const handleLogout = async () => {
    await sessionStorage.removeItem('user');
    navigate('/');
  }

  return (

Expense

<Link to='/'>Home</Link>

<Link to='/dashboard'>Dashboard</Link>

<Link to='/signup'>Signup</Link>

          { user && <button onClick={handleLogout}>Logout</button> }
          { !user &&
<Link to='/login'>Login</Link>
}

      <GiHamburgerMenu size={25} color='#333333' className='headerMenu' onClick={handleHeader}/>

  )
}

export default Header

A: Use callback function
You can achieve this by passing data from child to parent
import { useEffect, useState } from "react";
import Login from "./Login";
import "./styles.css";

export default function App() {
  const [user, setUser] = useState(null);

  useEffect(() => {
    getUser();
  }, [user]);

  const getUser = async () => {
    const currUser = await sessionStorage.getItem("user1");
    const jsonObj = JSON.parse(currUser);
    if (jsonObj != null) {
      setUser(jsonObj.userName);
    }
  };

  const handelLogout = async () => {
    await sessionStorage.removeItem("user1");
    setUser(null);
  };

  return (

        {user ? (
          <>

Hello {user}!!!

            <button onClick={handelLogout} className="logout">
              Logout
            </button>
          </>
        ) : (
          <Login getUser={getUser} />
        )}

  );
}

import { useState } from "react";

const Login = ({ getUser }) => {
  const [userName, setUserName] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!userName && !password) {
      setError("Please fill all credentials");
    } else {
      sessionStorage.setItem("user1", JSON.stringify({ userName, password }));
      getUser();
    }
  };

  return (
    <>
      <form onSubmit={handleSubmit} className="formBlock">

Login

        <input
          type="text"
          placeholder="username"
          value={userName}
          onChange={(e) => setUserName(e.target.value)}
        />
        <input
          type="text"
          placeholder="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />
        {error && {error}}
        <button>Login</button>
      </form>
    </>
  );
};
export default Login;

DEMO
Hope this helps

A: Your getUser is an async function. You need either await it, or do then. Or remove the async.

A: The problem
This is because the header never get notified when the session storage get changed.
This runs only once on app initialization.
  useEffect(() => {
    // Get user from sessionstorage
    getUser();
  }, []);

So to change that you could use the context api. The session storage should only be used for app initialization, but not for keeping a dynamic state on runtime, because you will never get the changes unless you call sessionStorage.getItem
Here the docs of the context api: https://reactjs.org/docs/context.html
This will help to keep the state reactive in the app.
The solution
You need to create a context

*

*Create a context

export const UserContext = createContext([false, () => undefined]);

export const UserContextProvider = ({ children }) => {
 const [user, setUser] = useState(false);

 useEffect(() => {
   // Get user from sessionstorage
   getUser();
 }, []);

 return (
   <UserContext.Provider value={[user, setUser]}>
     {children}
   </UserContext.Provider>
 );
};

*Bind it to your app

<UserContextProvider>
 <App />
</UserContextProvider>

*Then you can use it in your components

const [user, setUser] = useContext(UserContext);


text:
Q: Problem with Writing Excel file multiple time My code is trying to Uploading the user data to an excel file. When user enter the data from the app for the first time, it writing the data to the excel file. But the problem came when the user try insert data for the second time. It just writing the same first line. Here is my code.
    public void LibrarianUpdateData(String Name,String IC,String Date){

    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet librarianSheet = wb.createSheet("Librarian");

    String[][] datatypes = {
            {Name,IC,Date}
    };

    int Rownum = librarianSheet.getLastRowNum();
    System.out.println(Rownum);
    System.out.println("Updating excel");
    System.out.println("Initial Array:");

    for(int i = 0 ; i < 3; i++){
        System.out.println(datatypes[0][i]);
    }

    for (String[] datatype : datatypes) {
        Row row = librarianSheet.createRow(Rownum++);
        int colNum = 0;
        for (String field : datatype) {
            Cell cell = row.createCell(colNum++);
            if (field instanceof String) {
                cell.setCellValue((String) field);
            }
        }
    }
    System.out.println(Rownum);
    try {

        // this Writes the workbook
        FileOutputStream out = new FileOutputStream(new File("AttendenceList.xlsx"));
        wb.write(out);
        out.close();
        System.out.println("AttendenceList.xlsx written successfully on disk.");
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

My brain says that the data writed the same line. Is my hypothesis right?
How to alter this code so it write the next line?


text:
Q: Never disable the numeric keypad under Windows 7 Is there any way to tell Windows 7 to never disable the numeric keypad?
My keyboard is a Microsoft Comfort Curve.

A: Only guessing, but how about a program to remap keys on your keyboard.
Remap the Num Lock key to something such that if you inadvertently hit it, it does something other then disable the numeric keypad.


text:
Q: is the maximal tensor product of compact operators an essential ideal? I'm searching for a counterexample for $C^*$-algebras $A$ and $B$ and essential ideals (I assume an ideal to be closed and only two-sided ideals) $I\subseteq A$, $J\subseteq B$ , such that the ideal $I\otimes_{max} J$ is not essential in the (maximal tensor product) -$C^*$-algebra  $A\otimes_{max} B$. I'm not sure if my idea works:
The algebra of compact operators $K(l^2(\mathbb{N}))$ is an essential ideal in the $C^*$-algebra of bounded linear operators on  $l^2(\mathbb{N})$, $B(l^2(\mathbb{N}))$. The reason is that $B(l^2(\mathbb{N}))$ has only the closed ideals $\{0\}$, $K(l^2(\mathbb{N}))$ and $B(l^2(\mathbb{N}))$, thus $K(l^2(\mathbb{N}))\cap M\neq 0$ for all closed nontrivial ideals $M\subseteq B(l^2(\mathbb{N}))$.
But is $K(l^2(\mathbb{N}))\otimes_{max} K(l^2(\mathbb{N}))$ essential in $B(l^2(\mathbb{N}))\otimes_{max} B(l^2(\mathbb{N}))$?
I don't think so, but I'm stuck to prove that there must be a nontrivial closed ideal $M$ in $B(l^2(\mathbb{N}))\otimes_{max} B(l^2(\mathbb{N}))$ such that $K(l^2(\mathbb{N}))\otimes_{max} K(l^2(\mathbb{N}))\cap M$ is trivial. For the proof it must be important that one takes the maximal norm-closure of $I\odot J\subseteq A\odot B$ ($\odot$ denotes the tensor product as $*$-algebras), because particularly the spatial tensor product satisfies that if $I$ is essential in $A$, $J$ essential in $B$, then $I\otimes_{min} J$ is essential in $A\otimes_{min} B$ (and here  is $B(l^2(\mathbb{N}))\otimes_{min} B(l^2(\mathbb{N}))\neq B(l^2(\mathbb{N}))\otimes_{max} B(l^2(\mathbb{N}))$. If my ideal don't work, what else can I do?
I appreciate your help.

A: My suggestion (I hope that nothing is wrong):
Let $$F:B(l^2(\mathbb{N}))\otimes_{max} B(l^2(\mathbb{N}))\to B(l^2(\mathbb{N}))\otimes_{min} B(l^2(\mathbb{N}))$$ be the canonical map and define $M:=\ker(F)$. Since $F$ is not injective, $M$ is nontrivial.
Claim: $K(l^2(\mathbb{N}))\otimes_{max} K(l^2(\mathbb{N})) \cap M = 0$.
First note that $K(l^2(\mathbb{N}))$ is nuclear (because it's a inductive limit of nuclear $C^*$-algebras) and simple, therefore $$K(l^2(\mathbb{N}))\otimes_{max} K(l^2(\mathbb{N}))\cong K(l^2(\mathbb{N}))\otimes_{min} K(l^2(\mathbb{N}))$$ is simple.
It follows
$K(l^2(\mathbb{N}))\otimes_{max} K(l^2(\mathbb{N})) \cap M=\ker(F_{|K(l^2(\mathbb{N}))\otimes_{max} K(l^2(\mathbb{N}))})=0$, because $F_{|K(l^2(\mathbb{N}))\otimes_{max} K(l^2(\mathbb{N}))}$ is nonzero and $\ker(F_{|K(l^2(\mathbb{N}))\otimes_{max} K(l^2(\mathbb{N}))})$ is an ideal in $K(l^2(\mathbb{N}))\otimes_{max} K(l^2(\mathbb{N}))$.


text:
Q: Node.js 18 JS File Can't Import JS File In Repo I am using these commands in /server/package.json to build and run my server code:
"start": "npm run compile && node ./dist/index.js",
"dev": "concurrently \"npm tsc --watch\" \"nodemon -q dist/index.js\""

These scripts build my JavaSCript from my TypeScript source just fine. But when node/nodemon runs /server/dist/index.js it errors with this error:
Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/Users/.../server/dist/graphql/typeDefs' imported from /Users/.../server/dist/index.js
I know the paths are correct: If I Cmd + click on the relative path ie ./graphql/typeDefs on line 9 of server/dist/typeDefs (where the error occurs) in VSCode it opens that file up in a new tab. The corresponding TS file that the JS is generated from: https://github.com/currenthandle/next-apollo/blob/jwt/server/src/index.ts#L10
If I switch the imports to requires then it works...
Can anyone see what is going wrong there? I'm using node.js version v18.12.1

package.json
{
  "name": "eth-saturday",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "compile": "tsc",
    "start": "npm run compile && node ./dist/index.js",
    "dev": "concurrently \"npm tsc --watch\" \"nodemon -q dist/index.js\""
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@apollo/server": "^4.2.2",
    "@prisma/client": "^4.7.1",
    "graphql": "^16.6.0",
    "jsonwebtoken": "^8.5.1",
    "next-auth": "^4.18.6",
    "zod": "^3.19.1"
  },
  "devDependencies": {
    "@rollup/plugin-typescript": "^10.0.1",
    "@types/node": "^18.11.13",
    "concurrently": "^7.6.0",
    "prisma": "^4.7.1",
    "rollup": "^3.7.3",
    "typescript": "^4.9.4"
  }
}

tsconfig.json
{
  "compilerOptions": {
    "rootDirs": ["src"],
    "outDir": "dist",
    "lib": ["es2020"],
    "target": "es2020",
    "module": "esnext",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "types": ["node"]
  }
}


text:
Q: html footer add it to end of line I have footer as below and it shows properly with company name added to left of footer line.

Company, Inc.

I want to add contact link at end of footer line which will be at end of line.
I tried this

Company, Inc.

phone number:123456789

But it gets stacked one below other

A: Use footer { display: flex; justify-content: space-between; } to put them on the same line, separated by all of the free space in the footer.

footer {
  display: flex;
  justify-content: space-between;
}

Company, Inc.

phone number:123456789

A:

Company, Inc.

phone number:123456789


text:
Q: Vimrc keymapping with an argument I'm using Vim.rails and trying to customize the configuration:
:Rcontroller name

This command will open up the name_controller file in Rails.
How could I map this command to a key such that I can specify whatever "name" controller to open? In other words, I would need to pass in an argument...
I'd like to use the mapping:
<leader>name

to run :Rcontroller name with a . Or
<leader>othername

to run :Rcontroller othername with a .

A: Here's one possible method that I can think of from my (limited) understanding of Vim. However, your binding will need to be predefined as something (i.e. you won't be able to just type the controller name with <leader>).
nnoremap <leader>R :Rcontroller<space>

When you press <leader>R, the command line will read :Rcontroller [], where [] is the current cursor. Then you should be able to easily type in whatever argument you'd like.


text:
Q: Equations for points to lie on a rational normal curve $\def\PP{\mathbb{P}}$Let $z_1$, $z_2$, ..., $z_n$ be points in $\PP^{k-1}$. I am interested in equations for when the $z_i$ lie on a rational normal curve (or degeneration thereof.)
Specifically, let $s: \PP^{k-1} \to \PP^{\binom{k+1}{2} - 1}$ be the $2$-uple Veronese. If the $z_i$ lie on a rational normal curve, then the $n \times \binom{k+1}{2}$ matrix $(s(z_1), s(z_2), \ldots, s(z_n))$ has rank $2k-1$.
Let $X$ be the subscheme of $(\PP^{k-1})^n$ where $\mathrm{rank}(s(z_1), s(z_2), \ldots, s(z_n)) \leq 2k-1$. Let $V$ be the subscheme of $(\PP^{k-1})^n$ obtained by taking the closure of those points that lie on a degree $k-1$ rational curve. So $V \subset X$. If $k \leq 2$, this is trivial. If $k=3$, this says that $n$ points lie on a conic if and only if the $6 \times n$ matrix $(s(z_1), s(z_2), \ldots, s(z_n))$ has a right kernel -- again, this is obvious. So the first hard situation is $k=4$.
I would love it if $V=X$. That seems too good to be true, once $k \geq 4$, although I don't actually have a counter-example. Here are weaker things that would make me happy:

*

*Is $V$ an irreducible component of $X$?

*Is $X$ reduced at a generic point of $V$?

*Is there some explicit description of the other components of $V$?

A: Let me try the $\mathbb P^3$ case, and only look for a non-degenerate rational normal curve.  Apply a linear map to move the first four of your points to be the standard four points ($[1,0,0,0]$,...) (if the four are coplanar, they're not on an rnc).  Then apply the standard Cremona involution inverting each coordinate.  Do the remaining points become collinear?  If yes, they were on a rational normal curve (pre-Cremona).  If no, they weren't.  (For example, with six points, the remaining two are always collinear; not so with seven!)
I think this works the same in any dimension, at least generically.  If we're lucky, the closure of this relation (to include linearly degenerate configurations) will be the right equations to check if the points are on a degenerate rnc.

A: I would like to suggest the following paper, where my coauthors and I try to give a partial answer to this question
https://arxiv.org/abs/1711.06286
Roughly speaking, the idea is to use the Gale transform to reduce to the planar situation. In fact, one has that (d+4) points in P^d lie on a rational normal curve iff their Gale duals lie on a conic in P^2.

A: Uggh, I lose. $7$ generic points in $\mathbb{P}^3$ don't lie on a rational normal curve, but apparently they DO lie on $3$ quadratics. (Because we are looking at the kernel of a $10 \times 7$ matrix.)
That means there is some fun Chasles theorem stuff here: Any quadratic which passes through $7$ of the intersection points of three quadratics should pass through the $8$th.
So my specific suggestion of using quadratics was wrong. I'd be glad to hear any suggestions as to what is right.


text:
Q: Run command using rsh on a remote computer I am trying to run a python script, and I need to  Rsh a command from the script, the command I want to run is : df -Pk|grep "sd\|md"|gawk '{print $2}'
and I do it as -
cmd2='df -Pk|grep \\\"sd\|md\\\"|gawk \'{print $2}\''
process = subprocess.Popen(['rsh',ip,cmd2],stdout=subprocess.PIPE)
output = process.communicate()[0]

However when I do run the script,I get nothing in output.
I am new to python and as far as I know, its a problem with the escape characters.
Any help would be great.
Note:
I have to use Rsh only and cannot use ssh
Thanks

A: Enclose the command, with proper shell quoting, in triple quote marks:
"""df -Pk|grep "sd\|md"|gawk '{print $2}'"""

See also the Python tutorial's bit on strings.


text:
Q: Modify Optaplanner Vehicle Routing Problem vehicleRoutingScoreRules.drl to erase Hard constraint I want to modify the optaplanner example vehicle routing problem to erase Hard contraint and convert it to vrp no cvrp. I try to comment Hard contraints at vehicleRoutingScoreRule.drl, but it does not change anything.
//############################################################################
// Hard constraints
// ############################################################################

/*rule "vehicleCapacity"
when
    $vehicle : Vehicle($capacity : capacity)
    accumulate(
        Customer(
            vehicle == $vehicle,
            $demand : demand);
        $demandTotal : sum($demand);
        $demandTotal > $capacity
    )
then
    scoreHolder.addHardConstraintMatch(kcontext, $capacity - $demandTotal);
end
*/

A: Done!, it was that in the classpath i didn't remove the optaplanner-examples.jar.
Thanks,


text:
Q: CSS Set height as % of container I have a HTML coded as;

Now if I give width of 25% to the left div, it takes it correctly (e.g. if container=1000px, it would give left a width of 250px)
But if I specify height as 25% to the right div, it does not calculate it correctly (It seems like it ignores the % height)
How do I make the child div % height to be calculated correctly?

A: As you did with the width, you have to define an height for the container.
See  http://fiddle.jshell.net/z9GY8/2/
Note:
Close your divs e.g.

 (edit : Close with
)

A: You are missing the closing tag of child div.
And as far as possible don't put % for any element. Give them particular measurement.

A: You need to close your div tags like so:

Also as said previously, it may be better in this example to use absolute measurements for your heights and widths,  like (250px), rather than percentages.

A: HTML doesn't have ability to calculate height by percentage. It impossible to do just with HTML.
You should use javascript (jquery) for this target.
Like this example:
$('div.right').heght($(document).height() / 100 * 25); // So it will be 25 %.


text:
Q: How to use a generic type parameter as type parameter for a property declared as an interface with type constraints? How do I declare and use generic interfaces (see namespace Sample2) to work in the same way as with classes in namespace Sample1?
I know there is a workaround (see namespace Sample2Modified) but that is not what I'm trying to achieve.

Works with classes
When using classes, this works fine:
namespace Sample1
{
    public class ClassContainer<T1, T2>
        where T1 : T2
    { }

    public class ClassParent
    { }

    public class ClassChild : ClassParent
    { }

    public class ClassSampleDoesWork<TItem>
        where TItem : ClassParent
    {
        ClassContainer<IEnumerable<TItem>, IEnumerable<ClassParent>> SomeProperty { get; set; }
    }
}

Does not work with interfaces
However, with interfaces the compiler gives this warning when declaring the property in ClassSampleDoesNotWork:
Error 16 The type 'System.Collections.Generic.IEnumerable<TItem>'
cannot be used as type parameter 'T1' in the generic type or method
'Sample2.IInterfaceContainer<T1,T2>'. There is no implicit reference
conversion from 'System.Collections.Generic.IEnumerable<TItem>' to
'System.Collections.Generic.IEnumerable<Sample2.IInterfaceParent>'.

Code:
namespace Sample2
{
    public interface IInterfaceContainer<T1, T2>
        where T1 : T2
    { }

    public interface IInterfaceParent
    { }

    public interface IInterfaceChild : IInterfaceParent
    { }

    public class ClassSampleDoesNotWork<TItem>
        where TItem : IInterfaceParent
    {
        IInterfaceContainer<IEnumerable<TItem>, IEnumerable<IInterfaceParent>> SomeProperty { get; set; }
    }
}

Modified version works, but this is not really what I want
If I modify the class to have TEnumerableOfItem instead of TItem, it works:
namespace Sample2Modified
{
    public interface IInterfaceContainer<T1, T2>
        where T1 : T2
    { }

    public interface IInterfaceParent
    { }

    public interface IInterfaceChild : IInterfaceParent
    { }

    public class ClassSampleModifiedDoesWork<TEnumerableOfItem>
        where TEnumerableOfItem : IEnumerable<IInterfaceParent>
    {
        IInterfaceContainer<TEnumerableOfItem, IEnumerable<IInterfaceParent>> SomeProperty { get; set; }
    }
}

A: Try to add class constraint to the TItem:
namespace Sample2
{
    public interface IInterfaceContainer<T1, T2>
        where T1 : T2
    { }

    public interface IInterfaceParent
    { }

    public interface IInterfaceChild : IInterfaceParent
    { }

    public class ClassSampleDoesNotWork<TItem>
        where TItem : class, IInterfaceParent
    {
        IInterfaceContainer<IEnumerable<TItem>, IEnumerable<IInterfaceParent>> SomeProperty { get; set; }
    }
}

This works because variance only works for reference-types (or there is an identity conversion). It isn't known that TItem is reference type, unless you add : class.
Read this article for more information.
Here is a sample code to demonstrate this behavior:
IEnumerable<Object> items = new List<int>(); // Compiler error.


text:
Q: Can I use two  addons in Bootstrap input group? I saw on the bootstrap site that you could use a addon-field so for example € or .00 is placed before and after a amount of money.
But now I wonder if I could do the same but then use the addon field to enter the amount of money afer the .
and if so, how can I do that ?
Roelof
Edit 1 : Here a example of a bootstrap input field : http://getbootstrap.com/components/#input-groups-basic. You see a part where the currency is placed , a white area which is a input-field and a area where .00 is placed. I want that part to be a input field also but keep the same layout.

A: Bootstrap doesn't support that. Custom CSS will be required. This is mentioned in the documentation:

Basic example
Place one add-on or button on either side of an input. You may also place one on both sides of an input.
We do not support multiple add-ons on a single side.
We do not support multiple form-controls in a single input group.


text:
Q: .useDefaultAccount() for GoogleApiClient not working properly I'm trying to initialize the History API from Google Play services. Now ever since we updated our app, the .useDefaultAccount() method is not working properly and the connection result fails. This will cause a login prompt to appear in our app, where the user needs the choose their account. We would like to prevent this. Is there a way to do that?
How we make the client object and connect it (inside an AsyncTask):
GoogleApiClient apiClient = new GoogleApiClient.Builder(context)
                    .addApi(Fitness.HISTORY_API)
                    .useDefaultAccount()
                    .build();
            ConnectionResult connectionResult = apiClient.blockingConnect();

            if (!connectionResult.isSuccess()) {
                if (connectionResult.hasResolution() && context instanceof Activity) {
                    try {
                        connectionResult.startResolutionForResult((Activity) context, 1);
                    } catch (IntentSender.SendIntentException e) {
                        // Utter Failure
                    }
                }
            }
            return null;

A: The Google API Client should be built on the onCreate method of the Activity, not inside the AsyncTask. Try to move the code block to the appropriate class. This may be the reason as to why you're getting the SendIntentException.

A: Make sure you are handling the account choice result correctly in onActivityResult(). If you have not connected to GoogleApiClient there, the dialog will keep showing up.


text:
Q: Added whitespace when putting brackets around fractions with splitfrac I'm using splitfrac from mathtools to break up a particularly long line in the numerator of a fraction. When I put brackets around the fraction, however, they leave a line of whitespace in the denominator, presumably to keep the fraction centred. Is there a way to get rid of this?
\begin{align*}
(Qg)'(x) &= \left( \E \left[
\frac{\sum_{I \in A_\xi} g(\psi_I (x, \xi)) \chi_{f_\xi(I)}(x)}
     {\abs{f'(\psi_I(x, \xi)}}
\right] \right)'
= \E \left[ \left(
\frac{\sum_{I \in A_\xi} g(\psi_I (x, \xi)) \chi_{f_\xi(I)}(x)}
     {\abs{f'(\psi_I(x, \xi)}}
\right)' \right] \\
&= \E \left[
\frac{ \splitfrac{ \left( \sum_{I \in A_\xi} g(\psi_I (x, \xi)) \chi_{f_\xi(I)}(x) \right)' \abs{f'(\psi_I(x, \xi))} }
                 {-\left( \sum_{I \in A_\xi} g(\psi_I (x, \xi)) \chi_{f_\xi(I)}(x) \right)  \abs{f'(\psi_I(x, \xi))}'}
     } {\abs{f'(\psi_I(x, \xi)}^2}
\right]
\end{align*}

A: To my (mathematically) untrained eye, the tall square brackets in the second row of your screenshot seem redundant and could be omitted without loss. However, just in case they're not redundant, I suggest you replace \left[ ... \right] with \begin{bmatrix} ... \end{bmatrix} and use \dfrac rather than "just" \frac. That said, I think the "look" of the third row is better, as it (a) aligns the expectations operator symbol with the horizontal bar of the fraction term and (b) uses delimiters to enclose the contents of the two-line numerator term.
The following screenshot shows four possible solutions: Your original form, a solution that uses a bmatrix environment, a solution that encases the two-line numerator term in parentheses, and finally a solution that simply does away with "outer" fences entirely.

\documentclass{article}
\usepackage{mathtools,amssymb}
\DeclareMathOperator{\E}{\mathbb{E}}
\DeclarePairedDelimiter{\abs}{\lvert}{\rvert}
\begin{document}
\begin{align*}
(Qg)'(x)
&= \E \left[
\frac{ \splitfrac{ \left( \sum_{I \in A_\xi} g(\psi_I (x, \xi)) \chi_{f_\xi(I)}(x) \right)' \abs{f'(\psi_I(x, \xi))} }
                 {-\left( \sum_{I \in A_\xi} g(\psi_I (x, \xi)) \chi_{f_\xi(I)}(x) \right)  \abs{f'(\psi_I(x, \xi))}'}
     } {\abs{f'(\psi_I(x, \xi)}^2}
\right] \tag*{awful!}\\
&= \E \begin{bmatrix} \dfrac{
   \splitfrac{ \bigl( \sum_{I \in A_\xi} g(\psi_I (x, \xi)) \chi_{f_\xi(I)}(x) \bigr)'
                \, \abs[\big]{f'(\psi_I(x, \xi))} }
             {-\bigl( \sum_{I \in A_\xi} g(\psi_I (x, \xi)) \chi_{f_\xi(I)}(x) \bigr)
                   \abs{f'(\psi_I(x, \xi))}'}
     } {\abs[\big]{f'(\psi_I(x, \xi)}^2}
\end{bmatrix} \tag*{not awful} \\
&= \E \frac{ \left(
   \splitfrac{ \bigl[ \sum_{I \in A_\xi} g(\psi_I (x, \xi)) \chi_{f_\xi(I)}(x) \bigr]'
                \, \abs[\big]{f'(\psi_I(x, \xi))} }
             {-\bigl[ \sum_{I \in A_\xi} g(\psi_I (x, \xi)) \chi_{f_\xi(I)}(x) \bigr]
                   \abs[\big]{f'(\psi_I(x, \xi))}' }
     \right)} {\abs[\big]{f'(\psi_I(x, \xi)}^{2\mathstrut}} \tag*{better}  \\
&= \E \frac{
   \splitfrac{ \bigl[ \sum_{I \in A_\xi} g(\psi_I (x, \xi)) \chi_{f_\xi(I)}(x) \bigr]'
                \, \abs[\big]{f'(\psi_I(x, \xi))} }
             {-\bigl[ \sum_{I \in A_\xi} g(\psi_I (x, \xi)) \chi_{f_\xi(I)}(x) \bigr]
                   \abs[\big]{f'(\psi_I(x, \xi))}' }
     } {\abs[\big]{f'(\psi_I(x, \xi)}^{2\mathstrut}} \tag*{best(?)}
\end{align*}
\end{document}


text:
Q: unprintable python unicode string I retrieved some exif info from an image and got the following:
{ ...
37510: u'D2\nArbeitsamt\n\xc3\x84nderungsbescheid'
...}

I expected it to be
{ ...
37510: u'D2\nArbeitsamt\nÄnderungsbescheid'
... }

I need to convert the value to a str, but i couldn't manage it to work. I always get something like (using python27)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 14-15: ordinal not in range(128)

Any ideas how I can handle this?
UPDATE:
I tried it with python3 and there is now error thrown, but the result is now
{ ...
37510: 'D2\nArbeitsamt\nÃ\x84nderungsbescheid',
... }

which is still not the expected.

A: It seems to be utf8 which was incorrectly decoded as latin1 and then placed in a unicode string. You can use .encode('iso8859-1') to reverse the incorrect decoding.
>>> my_dictionary = {37510: u'D2\nArbeitsamt\n\xc3\x84nderungsbescheid'}
>>> print(my_dictionary[37510].encode('iso8859-1'))
D2
Arbeitsamt
Änderungsbescheid

You can print it out just fine now, but you might then also decode it as unicode, so it ends up with the correct type for further processing:
>>> type(my_dictionary[37510].encode('iso8859-1'))
<type 'str'>
>>> print(my_dictionary[37510].encode('iso8859-1').decode('utf8'))
D2
Arbeitsamt
Änderungsbescheid
>>> type(my_dictionary[37510].encode('iso8859-1').decode('utf8'))
<type 'unicode'>


text:
Q: How to include the squared symbol in a graph label I want to plot the value of R2 in my graph, but I don't know how to write the "2" as an exponent. How can I do that? Below you can find the code and the plot.
plt.figure()
plt.plot((y_train1),(y_train_pred),'.', color='darkviolet', alpha=1, marker='o', markersize = 2, markeredgecolor = 'black', markeredgewidth = 0.1)
plt.plot((np.array((-0.1,7))),(np.array((-0.1,7))),'-', color='magenta')
plt.xlabel('True')
plt.ylabel('Predicted')
plt.title('Train')
plt.text(5, 1, "R2 score EO: {:0.2f}".format(r2_train_EO), style='italic')

A: While the answer referencing latex would work - having to install latex for such a small change is a lot of hassle. This could be achieved by just using the unicode squared symbol in the label string:
plt.text(5, 1, u"R\u00b2 score EO: {:0.2f}".format(r2_train_EO), style='italic')

A: You should configure pyplot to use Latex:
from matplotlib import rc
rc('text', usetex=True)

Then write R^2 in your label.
Edit: the above is recommended if you also want to control fonts. If that is not needed, just write '$R^2$' in your text - this is also Latex.


text:
Q: Converting std::unique_ptr to std::unique_ptr Using C++11, let's say I have factory functions dealing with base and derived classes:
#include <memory>

using namespace std;

struct B { virtual ~B() {} };
struct D : B {};

unique_ptr<B> MakeB()
{
    auto b = unique_ptr<B>( new B() );
    return b; // Ok!
}

unique_ptr<B> MakeD()
{
    auto d = unique_ptr<D>( new D() );
    return d; // Doh!
}

On the last line above, I need move(d) in order to make it work, otherwise I get "Error: invalid conversion from std::unique_ptr<D> to std::unique_ptr<D>&&." My intuition said that in this context, the compiler should know that it could implicitly make d an rvalue and move it into the base pointer, but it doesn't.
Is this a non-conformancy in my compilers (gcc 4.8.1 and VS2012)? The intended design of unique_ptr? A defect in the standard?

Update: C++14 fixes this. Newer compilers such as GCC 9 accept the original code even with -std=c++11.

A: The compiler's behaviour is correct. There is only an implicit move when the types are the same, because implicit move is specified in terms of the compiler failing to perform copy elision in cases where it is actually allowed (see 12.8/31 and 12.8/32).
12.8/31 (copy elision):

in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) with the same cv-unqualified type as the function return type...

12.8/32 (implicit move):

When the criteria for elision of a copy operation are met, [...], overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue.

A: With the addition of the std::move calls in the return statements, this code works for me on Visual Studio 2013:
#include <memory>

using namespace std;

struct B { virtual ~B() {} };
struct D : B {};

unique_ptr<B> MakeB()
{
  auto b = unique_ptr<B>( new B() );
  return std::move( b );  // *** std::move() added here! ***
}

unique_ptr<B> MakeD()
{
  auto d = unique_ptr<D>( new D() );
  return std::move( d );  // *** std::move() added here! ***
}

The following also works
unique_ptr<B> MakeB()
{
  return unique_ptr<B>( new B() );  // *** Returning a temporary! ***
}

unique_ptr<B> MakeD()
{
  return unique_ptr<D>( new D() );  // *** Returning a temporary! ***
}

Of course, if you're returning std::unique_ptr<B> anyway, why not shove the D instance into a std::unique_ptr<B> in the first place?  Then there's no conversion necessary at all!


text:
Q: How does a JSON Web Token verify users on authentication? How does a JSON Web Token verify a user on authentication? Does the JWT store user data?
If so, how can I get a list of users who have done authentication?

A: In the context of token-based authentication, a token is a piece of data that identifies a user, working as a credential to perform authentication.

JWT is a self contained token that contains three parts:

*

*Header

*Payload

*Signature

The payload contains a set of claims and you can use it to store any arbitrary data.
The integrity of the token can be checked by verifying the signature that is generated on server side with a private key, using both header and payload encoded as Base64. JWT allows you to perform stateless authentication, that is, you don't need to store anything on server side besides the key used to sign the token.

sub is the standard payload claim to store the principal who is the subject of the JWT (the user who the token was issued for):

4.1.2.  "sub" (Subject) Claim
The sub (subject) claim identifies the principal that is the
subject of the JWT.  The claims in a JWT are normally statements
about the subject.  The subject value MUST either be scoped to be
locally unique in the context of the issuer or be globally unique.
The processing of this claim is generally application specific.  The
sub value is a case-sensitive string containing a StringOrURI
value.  Use of this claim is OPTIONAL.


text:
Q: Python compare each row, if it have same value A, then plus value B I have data that have thousand row, therefore I want to compare some row that have same value and meaning and sum their other values into one row.
14:45:14  923.0  6.9  4,399  87,144
14:30:02  923.9  7.8  6  82,745
14:30:00  924.0  7.9  19  82,739
14:29:58  924.0  7.9  1  82,720
14:29:56  924.0  7.9  20  82,719
14:29:54  923.9  7.8  96  82,699

my code
while True:

    dong_khop_lenh = driver.find_element_by_xpath(
                     "//div[@id='derivative-info-table-scroll-area-VN30F1910']" +
                     "/table/tbody/tr["+str(vitri1)+"]")
    tds = dong_khop_lenh.find_elements_by_tag_name('td')

    time_khop = tds[0].text
    gia_khop = tds[1].text
    lech_vn30 = tds[2].text
    kl_khop = tds[3].text
    kl_tluy = tds[4].text

    dong_khop_lenh_duoi = driver.find_element_by_xpath(
                     "//div[@id='derivative-info-table-scroll-area-VN30F1910']" +
                     "/table/tbody/tr["+str(vitri2)+"]")
    tds_duoi = dong_khop_lenh_duoi.find_elements_by_tag_name('td')

    time_khop_duoi = tds_duoi[0].text
    gia_khop_duoi = tds_duoi[1].text
    lech_duoi = tds_duoi[2].text
    kl_khop_duoi = tds_duoi[3].text
    kl_tluy_duoi = tds_duoi[4].text

    if float(gia_khop) == float(gia_khop_duoi) and \
       int(kl_tluy.replace(',', '')) > int(kl_tluy_duoi.replace(',', '')):
        vitri1 += 1
        vitri2 += 1
        kl_khop1 = int(kl_khop_duoi.replace(',', ''))
        if float(gia_khop) == float(gia_khop_duoi):

            final_kl_khop_duoi = int(kl_khop1) + int(kl_khop_duoi.replace(',', ''))
            final_dong_khop_lenh_duoi = str(time_khop) + "->" + str(time_khop_duoi) + \
                                "\t" + str(gia_khop_duoi) + "\t" + str(lech_duoi  ) + \
                                "\t" + str(final_kl_khop_duoi) + "\t" + str(kl_tluy_duoi)

            print final_dong_khop_lenh_duoi

I tried to compare rows 3 4 5 which have same value at 924, then plus 19+1+20
the result:
14:30:02    923.9   7.8 6   82,745
14:30:00    924.0   7.9 19  82,739
14:30:00->14:29:58  924.0   7.9 2   82,720
14:29:58->14:29:56  924.0   7.9 40  82,719
14:29:54    923.9   7.8 96  82,699
14:29:52    924.0   7.9 3   82,603
14:29:52->14:29:50  924.0   7.9 34  82,600
14:29:50->14:29:48  924.0   7.9 66  82,583
14:29:48->14:29:46  924.0   7.9 126 82,550


text:
Q: setTimeout runs function immediately I am trying to use 'setTimeout' to run 'window.open' function after certain period of time. If I calculate the time difference with the parent's property and then use the output for 'setTimeout', the 'window.open' function runs immediately. However, if I just give a number to the variable 'diffms', it works fine.
I am using react and how can I fix this problem?
// const diffms = 10000;
const diffms = moment(this.props.schedule.time).diff(moment());
  setTimeout(() => {
    window.open("https://www.google.com");
}, diffms);

A: SetTimeout has Maximum Delay Value
Browsers including Internet Explorer, Chrome, Safari, and Firefox store the delay as a 32-bit signed integer internally.
This causes an integer overflow when using delays larger than 2,147,483,647 ms (about 24.8 days), resulting in the timeout being executed immediately.
Please check more details here:
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#:~:text=Maximum%20delay%20value&text=This%20causes%20an%20integer%20overflow,the%20timeout%20being%20executed%20immediately.


text:
Q: Search strings that have a specific prefix xxx* In my data base, I have a field date_ID with a strings as follows:
  ----------------------------------
+              date_ID              +
  ----------------------------------
  111-11-333   555+33+22    -00000
  111-22-333   555+33+22    -00569      -- > element 1
  111-05-333   555+33+22    -00789
  111-22-333   555+33+22    -00008      -- > element 2
  111-22-333   555+33+22    -00001      -- > element 3
  111-22-111   555+33+22    -00001      -- > element 4
  ----------------------------------

How can I select all date_ID strings, that contains 111-22 as the prefix?
Table is dynamic. I'm new to mySql, so please help.
UPDATED QUESTION
I'm doing it in iOS, so I'm confused with the syntax too. So, pls help me to get the string as the form below.
NSString *passedPrefix = @"111-22";
[NSString stringWithFormat:@"select * from my_table WHERE date_ID LIKE \"%@\"",passedPrefix]
// How to add that last '%' here?

A: Just use the LIKE operator:
SELECT * FROM mytable WHERE date_id LIKE '111-22%'

A: In normal SQL you would use:
SELECT * FROM myTable WHERE date_ID LIKE '111-22%'

But as you've asked how to use this in iOS stringWithFormat, I think this is how:
WHERE date_ID LIKE '%@%%'

According to my source, you don't need to escape with backslashes.
I know nothing about iOS development, I literally did a Google search for you.


text:
Q: Flask-Login login_manager.session_protection=strong doesn't redirect to login page We're using flask-login to handle logins to our webpage. We expect it to be very strict with sessions so when a browser is closed, the user is prompted to log back in again.
We expect user would be sent to the login page for every url, and the session won't persist.
We require strict protection
login_manager.session_protection = "strong"
login_manager.refresh_view = "users.login"

Refresh view is used as the docs state:
refresh_view
The name of the view to redirect to when the user needs to reauthenticate

When the user closes their browser and begins a new session, they are not prompted to login, instead they're given a page where href's redirect to the login page, and other links give permission errors. This isn't optimal.
Internally, the way redirects are accomplished is with flask_login is by using the unauthorized() function in the login_manager.py file, which uses the request library to grab the request url of the page the user is trying to access. When an user is logged out trying to access the page it will properly grab the correct url and redirect the user to the variable assigned to the login_view setting. However, when session protection is set to strong and the user quits the application and redirects to the page, the unauthorized() function is not being executed.
So why aren't they sent to the login page every new browser instance?

A: In our case, the user still had a remember me cookie that persisted the session. After adding this line
REMEMBER_COOKIE_DURATION = timedelta(minutes=0)

The user is correctly sent to the login page.


text:
Q: How's to use the values of a Matrice on a recursion or a function method? I need to make a Sum of the columns of a Matrice, but, I need to use a function or method. I can't make the sum on " public static void main(String[] args)".
I'm reading the values for the matrice, but I'm having troubles to send the values for and static method or a function?
How I can solve this problem?
public class QuadMagico {
static int sumcolumns (int S[N]){
    return 0;
}

    public static void main(String[] args) {

    int N;
    Scanner sc1 = new Scanner(System.in);
    N = sc1.nextInt();
    N++;
    int D[][] = new int[N][N];
    for (int i = 1; i < D.length; i++) {
        for (int j = 1; j < D.length; j++) {
            D[i][j] = sc1.nextInt();
        }
    }

A: All your code should be completely error free, except this line. static int sumcolumns (int S[N])
The solution? Remove the N in S[N]. It looks like this. static int sumcolumns (int S[]) Then, you are free to call the method whenever.


text:
Q: ORA-22288: file or LOB operation FILEOPEN failed I have xml file abc.xml in \\192.168.1.71\err_log
I did below steps and getting error:
create directory XMLDIR2 as '\\192.168.1.71\err_log';

GRANT ALL ON DIRECTORY xmldir2 TO PUBLIC;

INSERT INTO example2
VALUES ( xmltype (
           bfilename('XMLDIR2', 'abc.xml'),
           nls_charset_id('AL32UTF8')
         )
       );

Getting below error:
ERROR at line 4: ORA-22288: file or LOB operation FILEOPEN failed
ORA-06512: at "SYS.XMLTYPE", line 296 ORA-06512: at line 1


text:
Q: Blazor Page Loaded before localstorage executes and fails to refresh My simple blazor.razor page can read local storage but seems to do after page is displayed. It takes a button to retrieve value. Seems like I should be able to force a refresh. But how ?

LocalStorageWithBlazoredStorage

@if (storeValue!=null && storeValue.Length>0)
{

 Current stored value is  @storeValue.

}
else
{

 Current stored value for user not set

}

Remember for 2 weeks or be subject to 2 factor authentication each time

    <input class="form-check-input" type="checkbox" value="" onclick="@SaveTwoFactorContactInfo" id="flexCheckDefault">

        Remember this computer

<button type="button" class="btn-success" onclick="@ReadLocalStorage">Read Local Storage</button>

@code {

    private string storeValue = string.Empty;

    private ContactInfo twoFacInfo = new ContactInfo();
    private const string TwoFactor = "TwoFactorVerifInfo";
    private void SaveTwoFactorContactInfo()
    {

        // persist an object
        ContactInfo twoFacInfo = new ContactInfo
        {
                LastName = "Jones",
                TextNumber = "425-123-4567",
                trustThisPc = true
        };

        localStorage.SetItemAsync(TwoFactor, twoFacInfo);

    }

    private async Task ReadLocalStorage()
    {
        twoFacInfo = await localStorage.GetItemAsync<ContactInfo>(TwoFactor);
        storeValue = $"Stored value for {twoFacInfo.LastName} {twoFacInfo.TextNumber} chose trust this PC : {twoFacInfo.trustThisPc}";
    }

    protected override async Task OnInitializedAsync()
    {
        ReadLocalStorage();// page start
    }

    protected async override Task OnAfterRenderAsync(bool firstRender)   // this doesnt update the page on load either
    {    // this fires again when click is done, firstRender is false but storeValue already loaded
        if (firstRender)
        {
            twoFacInfo = await localStorage.GetItemAsync<ContactInfo>(TwoFactor);
            storeValue = $"Stored value for {twoFacInfo.LastName} {twoFacInfo.TextNumber} chose trust this PC : {twoFacInfo.trustThisPc}";
            Console.WriteLine(" Ok");

        }
    }type here

A breakpoint shows page displayed and OnAfterRenderAsync fires but seems to late...
2nd how can I read the value firstRender. ? Is it possible to read
Expecting to not use a button to retrieve localStorage values
Googled StackOverflow  came upon similar issue...but only seems to work if called again...

A: Heyo, you're right that the local storage is being accessed after the page loads, because that's exactly what you've programmed to happen. The OnAfterRender method is fired after the page has rendered/loaded. Why don't you access the local storage in the OnInitialized or, since you seem to need the Async, OnInitializedAsync?
Also, to answer your question of

how can I read the value firstRender. ? Is it possible to read

Yes, it's possible to read, you can use a Console.WriteLine(FirstRender) for that and it'll show in your website's console. However there's no reason to read it if you know what it does. The bool FirstRender is of value true on the very first render of the page, so when the page is initially visible to the user.
Also, I noticed your OnInitalized method was wrong; no big deal. You just need to await your ReadLocalStorage method because it is of type async Task

protected override async Task OnInitializedAsync()
{
    await ReadLocalStorage();// page start
}

Your comments also say

this doesnt update the page on load either

And if that's true, you should be able to add a StateHasChanged method to your OnAfterRender method. I'll show it here:

    protected async override Task OnAfterRenderAsync(bool firstRender)   // this doesnt update the page on load either
    {    // this fires again when click is done, firstRender is false but storeValue already loaded
        if (firstRender)
        {
            twoFacInfo = await localStorage.GetItemAsync<ContactInfo>(TwoFactor);
            storeValue = $"Stored value for {twoFacInfo.LastName} {twoFacInfo.TextNumber} chose trust this PC : {twoFacInfo.trustThisPc}";
            Console.WriteLine(" Ok");
            StateHasChanged();
        }
    }

The StateHasChanged method is provided by ASP.NET and it essentially tells Blazor to reload the components because something has changed that can effect them.
Hope this helps!


text:
Q: KafkaJs - running consumers in background I'm writing a service which implements 2 consumers using Node and kafkajs
https://kafka.js.org/docs/consuming
I have 2 async function which have initialized consumers and in theory are pending to read messages. Something like this:
const { Kafka } = require('kafkajs')

// Create the client with the broker list
const kafka = new Kafka({
  clientId: 'my-app',
  brokers: ['kafka1:9092', 'kafka2:9092']
});
const consumer = kafka.consumer({ groupId: 'my-group' });

const consumerModule = async (): Promise<void> => {

 await consumer.connect();
 await consumer.subscribe({ topic: 'topic-A' });

 await consumer.run({
    eachMessage: async ({ topic, partition, message }) => {
        console.log({
            key: message.key.toString(),
            value: message.value.toString(),
            headers: message.headers,
        })
    },
 });
}

export default consumerModule;

If I want the consumer to run in the background in the service, should I just import the module file when I initialize the server?
I have a feeling that this will not work, because a call to consumerModule function must be made and because it's async, not sure how to implement it properly.
For example:
import express, { Express } from 'express';
import consumerModuleA from './modules/consumerModuleA';
import consumerModuleB from './modules/consumerModuleB';

async function bootstrap(): Promise<Express> {

    const app = express();

    app.get('/health', (_req, res) => {
        res.send('ok');
    });

    return app;
}

Please advise.

A: i would suggest the below. Notes:

*

*you can reuse the implementation of the consumer, by parametrizing the topic/group/etc).

*explicitly call the consumer module to run it.

import express, { Express } from 'express';
import consumerModule from './modules/consumerModule';

consumerModule();

async function bootstrap(): Promise<Express> {

    const app = express();

    app.get('/health', (_req, res) => {
        res.send('ok');
    });

    return app;
}


text:
Q: Cannot open virtual console 7 (Permission Denied) when trying to start X on Gentoo When I try to start X with i3 by typing startx /usr/bin/i3 I get the following error message:
 (EE) xf86OpenConsole: Cannot open virtual console 7 (Permission denied)
Launching startx as root or after chowning /dev/tty7 solves it (expect for input not working, not even switching terminals), but I don`t think that is the proper way to do that.
Sway and Weston work flawlessly why won`t X do so?

A: startx works fine on my system (Fedora).  However, one outdated page on the Gentoo Wiki mentions a different way to run it:
startx /usr/bin/i3 -- vt1

1 is the number of the "terminal" you are logged in on.  If you are not on terminal 1, then adjust the command accordingly.
Apparently this fixed the Permission denied error, and allowed X to start.
I don't understand why startx would need this to be passed explicitly.  I don't understand how Gentoo could be doing anything differently to Fedora here.  Oh well.  At least it should stop startx / Xorg from trying to open tty7.  That was definitely not the modern way to do things, and it was not working for you.

A: Cannot open virtual console (Permission denied) can also be caused by a permission issue on /dev/ttyX.
For instance on my openSUSE MicroOS before login:
$ ls -l /dev/tty1
crw--w---- 1 root tty /dev/tty1

but after login:
$ ls -l /dev/tty1
c--xr-xr-T 1 $USER tty /dev/tty1

The login utility is changing the owner of the TTY so you can type into it.
However in this case, it is also changing the permissions and read-write are no longer permitted!
Thus, startx shows the permission denied error because it can't write on the device.
Workaround
Change permission of the TTY before startx.
In my .zprofile:
# Auto-start Xorg when logging in on TTY1
check_tty() {
    local temp=$(tty)
    echo ${temp:5}
}

if [ $(check_tty) = "tty1" ]; then
    chmod 1600 /dev/tty1              # Notice the permission change before startx
    exec startx
fi

Possible cause
I could not find the exact cause of the issue.
It might be linked to systemd-logind as I also have the same ownership problem as this report and this one when startx fails.
I also investigated PAM and udev but nothing seems to change the /dev/tty mode to 1155 while it is happening in practice!


text:
Q: JavaScript not executing when dropdown option is changed I'm trying to work with JavaScript for the first time. I have gotten a dropdown list to do what I wanted thanks to help on this forum:
$('select').change(function(){
    const options = $("option");
    let selectedOption = "";
    let directDisplayString = "";
    options.each(function(index){
        let option = options[index];
        if($(option).prop("selected")) {
            selectedOption = $(option).val();
        };
        if(selectedOption === "450 Litre") {
            directDisplayString = '450 Litre Direct Storage Vessel with:';
        };
        if(selectedOption === "550 Litre") {
            directDisplayString = '550 Litre Direct Storage Vessel with:';
        };
        if(selectedOption === "900 Litre") {
            directDisplayString = '900 Litre Direct Storage Vessel with:';
        };
    });
    $("#directChoiceDisplay").empty().append(directDisplayString);
});

Now, I have dropdown lists on multiple webpages on my site. I wanted to do a similar thing for each page. When I have added more script to my JavaScript file, the second bit of code doesn't seem to execute:
$('select').change(function(){
    const options2 = $("option");
    let selectedOption2 = "";
    let stainlessDisplayString = "";
    options2.each(function(index){
        let option2 = options2[index];
        if($(option2).prop("selected")) {
            selectedOption2 = $(option2).val();
        };
        if(selectedOption2 === "3 kW 385 mm") {
            stainlessDisplayString = '3 kW 385mm immersed 2 1/4 BSP 1/3 Phase 240/415v';
        };
        if(selectedOption2 === "6 kW 385 mm") {
            stainlessDisplayString = '6 kW 385mm immersed 2 1/4 BSP 1/3 Phase 240/415v';
        };
        if(selectedOption2 === "9 kW 410 mm") {
            stainlessDisplayString = '9 kW 410mm immersed 2 1/4 BSP 1/3 Phase 240/415v';
        };
        if(selectedOption2 === "12 kW 585 mm") {
            stainlessDisplayString = '12 kW 585mm immersed 2 1/4 BSP 3 Phase 415v';
        };
    });
    $("#stainlessChoiceDisplay").empty().append(stainlessDisplayString);
});

I'm guessing my problem is ambiguity in the names of the different dropdown lists or something like that. I've tried to play around with names to fix it, but to no avail.
Any help would be greatly appreciated.

A test version of the webpage that is not working is here.
(A version of the page that IS working is here).

A: First of all, as suggested in comments, you should wait for the document to load before registering those event handlers. Since youre using jQuery this can be done with simple:
$(document).ready(function(){
  //Put your code here
});

Secondly, this part of the code might be problematic:
const options2 = $("option");

Because it will select not only the options in the select you are changing, but ANY option elements you might happen to have in the page (i.e. if you have multiple select elems, it will select options of each one of them), better idea might be something like:
$('select').change(function(){
    var options = $(this).children('option');
    //rest of the code
});

That will select only the options belonging to the select you are changing.
Also, instead of using something like:
options2.each(function(index){
    let option2 = options2[index];
    if($(option2).prop("selected")) {
    ...
});

Use the second parameter of the .each() callback function (that function gets two parameters current item index and current item):
options2.each(function(index, elem){
    if (elem.prop('selected')) {
    ...
});

Lastly, since you are getting the options just to get the selected value, you can use the .val() on the select iself:
$('select').change(function(){
    $(this).val(); //this contains the current selected option value
});

@Edit:
Since you added links to the site, the problem with your code lies also in multiple $('select').change() definitions, since that means that for every select element change found on page each and every of those handlers will be run. What you should do instead, is for example add each of the selects an unique ID and then your code should look like:
$('#selectWithSomeID').change(function(){
    val directDisplayString = "",
        directDisplayExtras = "",
        directDisplayPrice = "";
    if ($(this).val() === "450 Litre"){
        directDisplayString = '450 Litre Direct Storage Vessel with:';
        directDisplayExtras = '50 Litre Expansion Vessel'+'
'+'1" Combination Valve (3 Bar PRV / 6 Bar SRV)'+'
'+'3/4" T&P Valve 90°C 7 Bar, 25 kW Discharge Rate'+'
'+'Tundish';
        directDisplayPrice = "ÂŁ2,750";
    }
    else if ($(this).val() === "somethingelse")
    ...
    $("#directChoiceDisplay").text(directDisplayString);
    $("#directChoiceExtras").text(directDisplayExtras);
    $("#directChoicePrice").text(directDisplayPrice);
});


text:
Q: Change visibility of forms depending on chosen option I'm making a research form which will display differently depending on the choice of a SELECT value. I have applied some jQuery tricks after searching through here. Unfortunately, it doesn't work at all. Here is my code:
HTML:
<select name="options" id="choice">
    <option value="0" selected="true">Choose...</option>
    <optgroup label='ABC'>
        <option value="1">...DEF</option>
        <option value="2">...GHL</option>
    </optgroup>
    <optgroup label="MNP:">
        <option value="3">X</option>
        <option value="4">Y</option>
        <option value="5">Z</option>
    </optgroup>
</select>
<form id="opt1" name="opt1" style="display: none">11111111</form>
<form id="opt2" name="opt2" style="display: none">22222222</form>
<form id="opt3" name="opt3" style="display: none">33333333</form>
<form id="opt4" name="opt4" style="display: none">44444444</form>
<form id="opt5" name="opt5" style="display: none">55555555</form>

JavaScript:
$("#choice").change(function() {
    $("form").hide();
    $("#opt" + $(this).val()).show();
});

A: Try this one
$(document).ready(function(){
 $('select').change(function() {
    //var selected = $(':selected', this);
    //alert(selected.closest('optgroup').attr('label'));
     $("form").hide();
    $("#opt" + $(this).val()).show();
});
});

DEMO here

A: A @guradio suggests, the code works fine in fiddle. To debug the issue try putting alerts or console.log() to know that the issue it. Hope you have the jQuery library added to your page.
Try these:
$("#choice").change(function() {
    alert('fine till here');
    $("form").hide();
    $("#opt" + $(this).val()).show();
});

A: Your code is working,I think you are missing  j query library on form. please add.
see jsfiddle.net/f5xuc0gh/


text:
Q: Why we can not say: $\lim_{x \to \infty} f(x)>\lim_{x \to \infty} g(x)$ Given are:
$\lim_{x \to \infty} f(x) = 0$
$\lim_{x \to \infty} g(x) = 0$  and
$$\lim_{x \to \infty}\frac{f(x)}{g(x)}=k>1$$

Question: Why we can not say: $$\lim_{x \to \infty} f(x)>\lim_{x \to \infty} g(x)$$

Because, for example if  $$\lim_{x \to \infty} f(x)=m$$
$$\lim_{x \to \infty} f(x)=n$$ and $$\lim_{x \to \infty}\frac{f(x)}{g(x)}=\frac mn=k>1$$
We can write:
$$\lim_{x \to \infty} f(x)>\lim_{x \to \infty} g(x)$$
Why? Or do I think I'm wrong?

A: Are you asking why we cannot say
$$0 = \lim_{x \to \infty} f(x) > \lim_{x \to \infty} g(x) = 0$$
namely why we cannot say
$$0>0$$
???
Moreover the fact that we also have
$$\lim_{x \to \infty}\frac{f(x)}{g(x)}=k>1$$
is not incompatible with the individual limits being zero. An easy example is
$$f(x) = a/x,\;\; g(x) =b/x,\;\; a>b>0, \;\;\; x \in \mathbb R_{++}$$
Here, we have
$$f(x) > g(x), \;\;\forall x$$
but their respective limits are equal.
Also, each separate function goes to zero... but their ratio is the constant $a/b$.
Think of the ratio as a new function $h(x) = f(x)/g(x)$ with its own properties, that do not necessarily transfer back to the individual elements forming the ratio.


text:
Q: How can I preset a value by default in p-dropdown? I am trying to preset a default value in the below p-dropdown.
[ item.component.html ]
<ng-template pTemplate="body" let-newItem>

        {{ newItem.Key }}
        {{ newItem.Value }}

</ng-template>

I am getting json data from API and the data looks like
[
    {
        name: "clutch",
        id: 1
    },
    {
        name: "hat",
        id: 2
    },
    {
        name: "jeans",
        id: 3
    },
]

This is a part of the .ts file.
[ item.component.ts ]
export class ItemComponent implements OnInit {
    itemLists: any[] = [];
    selectedId: any[] = [];

    constructor(
        private itemService: ItemService
    ){}

    ngOnInit(): void {
        this.getItems();
    }

    getItems() {
        this.itemService.getItemLists().subscribe(
          (res) => {
            this.itemLists = res;
          },
          (err) => {
            console.log(err);
          }
        );
    }

    selectItem(id: any){
        this.selectedId.push(id);
    }
}

When users open the template and go to the p-dropdown, I want "hat" to be already selected by default. How can I make this? Any help, please

A: using the two-way biding to set the default value
ex:

ex:
defaultValue= {
        name: "clutch",
        id: 1
    },

A:     getItems() {
    this.itemService.getItemLists().subscribe(
      (res) => {
        this.itemLists = res;
        this.selectItem(theIdOfYourDefaultItem);
      },
      (err) => {
        console.log(err);
      }
    );
}


text:
Q: TextView from Navigation Header is null I'm trying to implement a navigation drawer with NavigationView.
Everthing works fine so far, every item is displayed correctly. However there is a NullPointerException in this lines :
View header = navigationView.getHeaderView(0);
TextView username = (TextView) header.findViewById(R.id.profile_name_id);
username.setText(mUser.getUsername());

In this line username.setText(mUser.getUsername()); the NullPointerExption is thrown. The strange thing is that it still displays the correct text of mUser.getUsername()
This is the NavigationView:
<android.support.design.widget.NavigationView
        android:id="@+id/navigation_view"
        android:layout_height="match_parent"
        android:layout_width="wrap_content"
        android:layout_gravity="start"
        app:headerLayout="@layout/drawer_header"
        app:menu="@menu/drawer"/>

Drawer_header:
 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:paddingTop="20dp"
    android:paddingBottom="20dp"
    android:background="@color/primary_dark"
    android:layout_width="match_parent"
    android:layout_height="160dp">

    <ImageView
        android:id="@+id/profile_pic_id"
        android:src="@drawable/account_big"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:layout_height="0dp"/>
    <android.widget.TextView
        android:id="@+id/profile_name_id"
        android:textColor="@color/primary_text"
        android:textSize="18sp"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

Drawer:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">

        <item
            android:id="@+id/home_id"
            android:checked="false"
            android:icon="@drawable/home"
            android:title="@string/home" />

        <item
            android:id="@+id/create_set_id"
            android:checked="false"
            android:icon="@drawable/add_box"
            android:title="@string/create_learnset" />

        <item
            android:id="@+id/logout_id"
            android:checked="false"
            android:icon="@drawable/logout"
            android:title="@string/logout" />
    </group>
</menu>

A:
You need to only write Text View.

Change this
<android.widget.TextView
        android:id="@+id/profile_name_id"
        android:textColor="@color/primary_text"
        android:textSize="18sp"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

To this.
  <TextView
        android:id="@+id/profile_name_id"
        android:textColor="@color/primary_text"
        android:textSize="18sp"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

It's Done.


text:
Q: How to set opacity only on button text color without rgba? something like:
    background-color: #000;
    color: #fff;
    color-opacity: 0.5;

rgba unused, because all color in hex format.

A: You can use the 8-digit HEX code color like this:

div {
  background-color: #000;
  color: #ffffff80;
}

text

A: You could use an extra HTML element.

.button {
  background-color: #fff;
  color: #000;
}

.button > .text {
  opacity: 0.5;
}
<button class="button">

    Click me.

</button>


text:
Q: Can I build a pair of networks with a DNS server on a different network to the gateway? Network Diagram
[ISP] <-> [gateway] <-> (lan 1) <-> [Debian 10 desktop] <-> (lan 2) <-> [DNS Box]

*

*Lan 1: 192.168.0.X/24

*Lan 2: 192.168.1.X/24

*DNS Box has static IP 192.168.1.8/24

*It is connected via a crossover ethernet cable to my Debian 10 desktop, using its native eth port/interface and a USB eth interface on the Debian 10 box

*The Debian 10 box is then connected to the lan 1 network using its native eth interface/port

*Lan 1 contains a bunch of switches, all which connect to my ISP provided router, which is the gateway to the WAN
Typical Setup, reason why this one is different/weird
Typically my DNS box is on the same network as Lan 1. Usually I just plug it into the switch, then tell my Debian 10 machine to look for the DNS info at the ip 192.168.1.8. Usually I am on a network where all the devices are connected via switches, and are all on network 192.168.1.X.
However I temporarily moved elsewhere where the local lan is on 192.168.0.X, so I can't plug the DNS box into a switch.
Hence I set up a new static network to connect it to the Debian 10 box, using a spare USB adapter. I can ssh into it.
However it is not working as a DNS server. This is probably because:

*

*although DNS requests may currently being sent to it (I don't know if they are or not as I don't know how to test this)

*I don't think the DNS box knows how to access DNS servers on the WAN / wider internet, because it probably does not have a route to the wider internet

*In order to get this it probably needs me to set up my Debian 10 box as a router, to route traffic from the network 192.168.1.X/24 to 192.168.0.X/24

However please note the first bullet in that list, I am not sure if my hunch is correct here. It might be the case that what I am trying to do is impossible.
My current config / what I tried

*

*Debian 10 box has 2 wired network interfaces, they are connected as follows

*

*Interface A: "Eth DHCP"

*"Automatic (DHCP) Addresses Only"

*192.168.0.22/24

*DNS Servers: 192.168.1.8

*Interface B: "Eth DNS Box Static"

*"Manual"

*192.168.1.1/24

*Gateway: left blank (?)

*DNS Servers: blank/none

Next steps
At present I am not currently sure what diagnostics steps I should take.
Solution

*

*Change to root user and run echo 1 > /proc/sys/net/ipv4/ip_forward
Setup iptables as follows:

*

*sudo iptables -L (currently blank)

*sudo iptables --table nat --append POSTROUTING --out-interface enp3s0f2 -j MASQUERADE

*sudo iptables --append FORWARD --in-interface enx0050b668976b0j ACCEPT
This command failed because the network interface name enx0050b668976b0j is too long

*

*Tried changing this with a udev rule - that didn't appear to work

*Info here: https://unix.stackexchange.com/questions/396382/how-can-i-show-the-old-eth0-names-and-also-rename-network-interfaces-in-debian-9#396383

*Changed using iproute2, this may be temporary, not sure at the present time

*sudo ip link set enx0050b668976b down

*sudo ip link set enx0050b668976b name eth1

*sudo ip link set eth1 up
Then ran

*

*sudo iptables --append FORWARD --in-interface eth1 -j ACCEPT
Info for iptables from https://www.howtoforge.com/nat_iptables
Testing

*

*ssh'd into my DNS server, pinged 192.168.1.1 (next hop / debian box), 192.168.0.1 (next next hop / ISP router), 8.8.8.8 and google.com, all working ok

*Changed some settings on debian network config, including interface names, due to renaming interface to eth1, other than this all settings were fine

*Went to a few websites on the debian machine, all working ok

Output from sudo iptables -L
Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere

A: There are probably a few things you need to do and this still may not work.
Going from RIGHT.
DNS Box:

*

*It needs to list your Debian 10 as a router. You probably need to list 192.168.1.1 as a default gateway there.

Debian 10 Desktop:

*

*It needs a default gateway to be your ISP modem / router. This should be happening automatically as you claim to use DHCP there.

*You have to enable IP forwarding by writing 1 to /proc/sys/net/ipv4/ip_forward.

*You may need to properly configure firewall on that system.

ISP router / modem:

*

*You have to add the route to 192.168.1.0/24 network there and to list the IP address of the Debian 10 Desktop as the gateway. This may or may not be supported on that device and using DHCP for the Debian 10 Desktop is suboptimal here.

If the above is not a workable setup (i.e. because of router / modem limitations) your likely only options left are:

*

*Use NAT on Debian 10 Desktop. It has limitations on its own.

*Merge the two networks into one. Isn't it possible for your ISP router / modem to reconfigure for use of 192.168.1.0/24 network?


text:
Q: Cancel a PayPal order through API I have as shopping cart which uses PayPal Website Payments Standard,becasue of some reason i want to cancel a order in the paypal using Apis available in Paypal.
How can approach this?

A: When you say "cancel an order" do you mean you want to refund the payment?  If so, you can do this using the RefundTransaction API, or if you're using Adaptive Payments, the Refund API.


text:
Q: Could aliens observe Curiosity, the rover? Inspired by:

The color image, taken from a distance of 169 miles, is the combined view of three wavelength bands — red, blue-green and infrared.
Curiosity is not the only Earth visitor that has been spotted. In 2006, the orbiter took this image of the Opportunity rover, which showed not only the rover but also the tracks in the soil and even the shadow of its camera mast.

I'm going to guess no. The image is pretty small and poor resolution and it was taken at a range of 169 miles.
Would a very advanced camera be capable of capturing this small blue dot at a many light-year distance? Or are there limits to the capabilities of physics with regards to cameras?

A: In principle, this would be possible, but would require impractically big lenses, at least. The angular resolution of a telescope is limited by diffraction on camera lenses. The Rayleigh criterion states that two points emitting light of wavelength $\lambda$ can be distinguished from each other by a camera with aperture diameter $D$, if the angle, at which these dots appear, is no smaller than
$$
\sin \theta = 1.22 \frac{\lambda}{D}.
$$
By subsituting all of the lengths (say, the distance is one lightyear, which is $3 \cdot 10^8$ m, the Opportunity rover is about 2 m wide, and the average wavelength of visible light is about 0.5 $\mu$m), we obtain that the lens of such a telescope would have to be at least 75 m wide. We can assume though that the telescope is not optical but UV or something (so that the wavelength is smaller), but still the necessary size scales linearly with distance to the object. This effectively prevents aliens from seeing the rover. And that doesn't take into account positioning of the telescope, stability, etc. etc.


text:
Q: CXF doesn't honor keep-alive request by the client My client is sending:
POST /xxx/yyy HTTP/1.1
Host: localhost:9009
User-Agent: gSOAP/2.8
Content-Type: text/xml; charset=utf-8
Content-Length: 2442
Connection: keep-alive
SOAPAction: ""

But the server replies:
HTTP/1.1 200 OK
Content-Type: text/xml;charset=UTF-8
Content-Length: 11182
Server: Jetty(8.1.14.v20131031)

Isn't the server supposed to return "Connection: keep-alive" too?
I see that afterwards the client closes the connection although it is configure to keep the connection open.
I assumed it is because the server didn't provide the keep-alive in the reply (Is that the RFC?).

A: In my case the reason gSoap closed the connection wasn't related to the HTTP headers returned from server, but to the fact you need to specify the keep-alive flags on both directions by calling:
    soap_set_imode(this, SOAP_IO_KEEPALIVE);
    soap_set_omode(this, SOAP_IO_KEEPALIVE);

From what I've read in HTTP 1.1 persistent connections are the default so if the server didn't return "Connection: close" the connection can be used for next request too.


text:
Q: How Can I scroll page up after button click? I have this html code with registration form and I need scroll page up after the click on
button with class .reg. The problem is that the page scroll only to up border of form.
<div class='registration borders'>

<form action="{$web_path}/model/user/userRegistration.php" method="post">

<input class='user' type='text' name='user' autofocus required placeholder="uživatelské jméno">
<input class='email' type='email' name='email' required placeholder="Váš e-mail">

<input class='password' type='password' name='password' required placeholder="uživatelské heslo">

<button class='reg' type='submit' name='registration_sent'>ZAREGISTROVAT</button>

</form>

</div>

Javascript code
$(document).ready(function () {
    var button_reg = $('button.reg');
    button_reg.click(function () {

        // scroll top
        $('html, body').animate({
            scrollTop: 0
        }, 'slow');
    });

    // end jquery
    return false;
});

A: try something like this:
$(document).ready(function(){
$('#button').click(function(){
$('html, body').animate({scrollTop: $("#your_respective_div").offset().top}, 1000);
});
})


text:
Q: How to access a list of tibble to check whether "UTF-8" and run import R TARGET :
Check whether a list of files have same encoding before import and rbind ,if not the same STOP run
# files list & check encoding
FL_PATH <- list.files(path,pattern = "*.csv",full.name = T)
library(readr)
lapply(FL_PATH,guess_encoding)

# if there is "UTF-8" , STOP RUN , if "Shift_JIS" , RUN the next scripts below :

# import
library(rio)
DT <- rbindlist(lapply(FL_PATH ,import,sep=",",setclass = "data.table"))

# OVER 500 rows to run if the files are same encoding to rbind
DT[,"NEW_COL":="A"]
DT[,"NEW_COL_2":="B"]
.....

# result of --lapply(FL_PATH,guess_encoding)
> lapply(FL_PATH,guess_encoding)
[[1]]
# A tibble: 3 x 2
  encoding  confidence
  <chr>          <dbl>
1 Shift_JIS       0.8
2 GB18030         0.76
3 Big5            0.46

[[2]]
# A tibble: 3 x 2
  encoding  confidence
  <chr>          <dbl>
1 GB18030         0.82
2 UTF-8       0.8
3 Big5            0.44

*

*Problem 1 : How to access the variables of the result of lapply readr
to detect UTF-8 and STOP (have to revise the encoding outside R if
UTF-8 exist ?)

*Problem 2 : How to connect the large numbers of normal processing scripts
with "if & STOP run" ?

A: First, get the most probable encoding:
enc <- sapply(FL_PATH,function(x) guess_encoding(x)$encoding[1])

Then, if any of the files are UTF-8, stop execution.
if(any(grepl('UTF-8',enc)))
  stop('UTF-8 present') # This will stop with an error if true
# Now, read files and rbind
dlist <- lapply(FL_PATH,read_csv)
DT <- rbindlist(dlist)


text:
Q: How to derive the semigroup and infinitesimal generator for the compound Poisson process? Let $(N_t: t\geq0)$ be a Poisson process and $(Y_i)_{i\in\mathbb N}$ a series of i.i.d. integrable random variables on $\mathbb Z$. Put
$X_t = \sum_{i=1}^{N_t} Y_i$ for $N_t > 0$ and $X_t$ for $N_t=0$.

I want to formulate the forward and backward equations for the process $(X_t: t\geq0)$. But I'm stuck at finding its semigroup and generator (Q-matrix).

So I'm looking for
$$P'(t)=Q P(t),\ t\geq0, \qquad P(0)=\mathrm I \qquad \mathrm{(backward\ equation)}$$
and
$$P'(t)=P(t)Q,\ t\geq0, \qquad P(0)=\mathrm I \qquad \mathrm{(forward\ equation)}$$
where
$\left(P(t)\right)_{t\geq0}$ is the semigroup and $Q$ the Q-matrix of $(X_t)$.
I know the the Q-matrix and semigroup for the Poisson process $(N_t)$ are
$Q = \lambda(P-\mathrm I)$
and
$$P(t)=\mathrm e^{-\lambda t} \sum_{k=0}^\infty \frac{(\lambda t)^k}{k!}P^k$$
where $P$ is the matrix of transition probabilities (on a countable state space $S$).
For $(N_t)$ we have the backward equation given as
$$P'_{ij}(t)
=\sum_{k\in S}q_{ik}P_{kj}(t)
=\lambda P_{i+1,j}(t)-\lambda P_{ij}(t), \qquad t>0 \qquad \tag{1}$$
and the forward equation as
$$P'_{ij}(t)
=\sum_{k\in S}P_{ik}(t)q_{kj}
=\lambda P_{i,j-1}(t)-\lambda P_{ij}(t), \qquad t>0. \qquad \tag{2}$$
If I understand the definition correctly, then $(X_t)$ is similar to a Poisson process, but after its Exp($\lambda$) waiting time it doesn't jump deterministically $+1$, but according to the random variables $Y_i$. However, I don't know how to compute the semigroup and Q-matrix for $(X_t)$, nor can I find any suitable reference.
Can someone help me get there?

A: The miracle of infinitesimal generator is that it often tells you literally what is happening to you process. Here the generator is
$$
Qf(x) = \lambda\int_{\mathbb R} \big(f(y+x) - f(x)\big)F(dy).
$$
Let me decipher this for you. $\color{blue}\lambda$ before the integral is the jump intensity. The integrand tells you what to do: $\color{blue}{-f(x)}$ means removing the moving particle from its current location $x$. $\color{blue}{+f(x+y)}$ means placing the removed article to the new location $x+y$. $\color{blue}{F(dy)}$ means that the length $y$ of jump to new location should be chosen according to the distribution $F$.
In your particular case, where the jumps are integer valued (so that e.g. $P(Y_i = n) = a_n$, $n\in \mathbb{Z}\setminus \{0\}$), you'll get
$$
Qf(m) = \lambda\sum_{n\in\mathbb{Z}} a_n\big(f(m+n) - f(m)\big).
$$
The corresponding "matrix" is then equal to $[Q] = (q_{ij})_{i,j\in\mathbb Z}$ with
$$
q_{ij} = \begin{cases}
\lambda a_{i-j}, i\neq j,\\
-\lambda, i=j.
\end{cases}
$$
To find the semigroup, you need to identify $e^{tQ}$. This does not always have a nice form. In the case of usual Poisson process, the generator can be decomposed as $Q = -\lambda I + \lambda S$, where $S$ is the right shift. Since these two operators commute, $$
e^{tQ} = e^{-t\lambda I} e^{-t\lambda S} = e^{-\lambda t}\sum_{n=0}^\infty \frac{(\lambda t)^n}{n!}S^n;
$$
here you can clearly see that the increments of your process have Poisson distribution (as expected).
For a general compound Poisson process you may write your answer as some mixture of convolutions of $Y$ with Poissonian weights, but this is not very exciting.


text:
Q: Why can't I evaluate "array to NULL" in a for loop? I'm trying to count the elements of the array's arrays for the allocation of memory "res," used to concatenate, including NULL terminators, every string stored in "argv". There are probably more bugs to be found, but the first I don't understand is argv[a][b] != NULL in /* length of arrays */. Why isn't this acceptable and are there other ways --without hardcoding- or passing length-- to determine number of elements?
used: http://pythontutor.com/c.html#mode=edit
char    *ft_concat_params (int argc, char **argv)
{
    int len_argc = argc - 1,
        len_argv = 0;
    char *res = NULL;

    /* length of argvs */
    for (int a = 0; a < len_argc; a++) {
      for (int b = 0;argv[a][b] != NULL; b++) {
        len_argv++;
      }
    }

    /* allocate memory res -- freed by calling function! */
    res = malloc (len_argv * sizeof * res);
    if (!res) {
      ft_putstr ("not allocated res");
      free(res);
      return NULL;
    }

    /* concate strings */
    for (int a = 0; a < len_argc; a++) {
      int b = 0;
      while (argv[a][b] != '\0') {
        res = &argv[a][b];
        b++;
      }
      res[b] = '\0';
    }

    return res;
}

int   main(void)
{
  int argc = 4;
  char argv[3][6] = {
    {'s','t','a','r','t','\0'},
    {'s','t','a','r','t','\0'},
    {'s','t','a','r','t','\0'}
  };
  char *arr;

  arr = ft_concat_params (argc, argv);
  if (!arr)       /* validate return */
      return 1;

  free(arr);
}

A: This line:
char *res = 'NULL';

Does NOT initialize the pointer to NULL.
Rather, it sets to some strange, non-sensical 32-bit value.
You want to start with
char *res = NULL;  // NOTE:  No single-quotes around it.

A: the first I don't understand is argv[a][b] != NULL

*

*argv has type (char **)

*argv[a] has type (char *)

*argv[a][b] has type (char)

Comparing argv[a][b] with NULL is comparing a char with a pointer, which is not allowed because it doesn't make sense.

A: The main problem is that a 2D array has nothing to do with a char**. A pointer to pointer cannot point at a 2D array. It is not a 2D array. It is not compatible with a 2D array. Forget about pointer to pointers.
Except when you have a 1D array of pointers - then a pointer-to-pointer can be used to point at the first element of that array. So if your code in main() had been char* argv[n] = { "hello", "world", ... } then your function with char** would have worked.
But it is not. You have a true 2D array in main(). So you have to change the function accordingly:
char* ft_concat_params (int x, int y, char argv[x][y])
{
  ...
  argv[i][j]  // now you can use this way of accessing


text:
Q: Automatically change format of protected methods I'm trying to use Mathematica for building complex derivatives for my Fortran code. Therefore I have to do some wild string replacements to make that work. Anyway, I got quite far already but now it would come in handy if I could automatically overwrite let's say the Power method.
What I want is that Mathematica should replace e.g. x^(1/4) with x**z14 on FortranForm. What does work is this:
i=1;
j=4;
Unprotect[Power];
Power /: Format[Power[x_, i/j], FortranForm]:=x^ToExpression["z" <> ToString[i] <> ToString[j]]
Protect[Power];

ToString[Power[x, i/j], FortranForm]

This will give x**z14 as expected.
If I try to automate the process for more fractions
Unprotect[Power];
For[i = 1, i <= 9, i++,
 For[j = 1, j <= 9, j++,
  If[j > 1 && j != i && Mod[i, j] != 0,
    Power /: Format[Power[x_, i/j], FortranForm]:=x^ToExpression["z"<> ToString[i] <> ToString[j]];
    ,Null
  ]
 ]
]
Protect[Power];

ToString[Power[x, i/j], FortranForm]

I get x**z1010 instead?
Can anyone help me and tell me what I'm doing wrong? Or is this even possible?
Thanks!

A: The problem is that the variables i and j on the RHS of the definition are not being bound to the input. A simpler example:
i=1; j=4;
foo[i/j] := {i, j}

DownValues[foo]

{HoldPattern[foo[1/4]] :> {i, j}}

You could workaround this by using With to inject the values of i and j into the RHS, but why aren't you using patterns instead? For example:
Unprotect[Power];
Format[Power[x_, Rational[i_, j_]], FortranForm] := x^ToExpression["z"<>ToString[i]<>ToString[j]]
Protect[Power];

Then:
ToString[x^(3/4), FortranForm]
ToString[x^(1/7), FortranForm]

"x**z34"
"x**z17"


text:
Q: Express-resource pass additional data from app.js to routes I would like to pass additional data from app.js to express-resource routes and I have not figured out yet. How would you do that? Note that I'm using express-resource
// app.js
var myAddOnData = 'abc';
app.resource('users', './routes/user');

// user.js
exports.index = function (req, res) {
   console.log(myAddOnData);
};

Thanks

A: These are the three approaches I can think of. Without the little I know about your specific problem, it sounds like middleware might be the way to do it.
With a global app variable
Create a value using app.set in app.js and then retrieve it using app.get in user.js.
Using a module
Store the information in an isolated module, then require() as needed. If this is running across multiple instances, you'd obviously want to store the values to disk as opposed to in memory.
// keystore.js
// -----------
module.exports.set = function(id, val) { /* ... */ };
module.exports.get = function(id) { /* ... */ };

// app.js
// -----------
var ks = require('./keystore');
ks.set = function("userInfo", "abc");
module.exports.get = function(id) { /* ... */ };

// user.js
// -----------
var ks = require('./keystore');
ks.get = function("userInfo", "abc");

(Maybe check out pot?)
Using Middleware
Use custom middleware to attach data to the request object which can then be accessed later in the route handlers.
//app.js
//------
var express = require('express')
  , cookieSessions = require('./cookie-sessions');

var app = express();

app.use(express.cookieParser('manny is cool'));
app.use(cookieSessions('sid'));
// ...

//cookie-sessions.js
//------------------
module.exports = function(name) {
  return function(req, res, next) {
    req.session = req.signedCookies[name] || {};

    res.on('header', function(){
      res.signedCookie(name, req.session, { signed: true });
    });

    next();
  }
}

via https://gist.github.com/visionmedia/1491756


text:
Q: How to add custom typing correctly for tests I wanted to define a global constant based on the webpack config.
Therefore I added the constant DEBUG to the DefinePlugin.
The said constant then should be used inside of some code, in my case inside of a service.
When doing npm run build I received an error, that the name DEBUG could not be found, so I added a custom-typings.d.ts which solved this.
But I still get the error, when running the tests.
Question is, how do I define custom typings so karma is using them as well? Or differently said, how can I make use of the custom-typings.d.ts when running the tests?
./webpack.config.js
    [...]
    new webpack.DefinePlugin({
        DEBUG: JSON.stringify(true)
    }),
    [...]

./src/app/services/SomeService
[...]
@Injectable()
export class SomeService {
    [...]
    private shouldStart() {
        return !(DEBUG);
    }
}

./src/custom-typings.d.ts
declare var DEBUG: boolean;
./src/test.ts
[...]
TestBed.initTestEnvironment(
    BrowserDynamicTestingModule,
    platformBrowserDynamicTesting()
);

// load all specs in ./src .
const context = (require as any).context('./', true, /\.spec\.ts$/);
context.keys().map(context);

./src/tsconfig.json
{
    "compilerOptions": {
        "baseUrl": "",
        [...]
    },
    "files": ["test.ts"],
    "include": ["**/*.spec.ts", "**/*.d.ts"]
}

Error thrown when running npm test
ERROR in [at-loader] ./src/app/some/some.service.ts:112:14
TS2304: Cannot find name 'DEBUG'.

(this error occurred in the building process as well before I had the custom-typings.d.ts)
EDIT: Added the paths for clarification as well as some more information

A: To answer for your specific project, I'd have to see where the custom-typings.d.ts file is in your project's file tree.
For a *.d.ts file to work, it needs to be located along-side your main entry point .ts file. If you use a baseUrl config in your tsconfig.json, it should be at the path you define there.
It should be included in your karma build automatically if the file is in the right path.


text:
Q: Why would SSDT show some minor changes for certain tables only? In my .sqlproj project I have a number of SQL database tables which have columns with default constraints such as:
 CREATE TABLE TableName
(
-- Some other columns defined too
[State] TINYINT NOT NULL DEFAULT (0),
)

When I run SSDT schema compare of the project against the production database the following happens. Some tables like the one above are reported having no differences and one is reported to have the following difference.
The comparison tool says that the project has this (and that's true and it's also true for all other tables):
-- Single braces around zero
[State] TINYINT DEFAULT (0) NOT NULL

but the database has this:
-- Double braces around zero
[State] TINYINT DEFAULT ((0)) NOT NULL

This is annoying because it causes a lot of useless changes being reported. It is even more annoying because I have something like ten tables with such column definition but differences are only reported for one table only.
I tried to open SSMS and right click the table in the production database and Script table as, CREATE To new window and it yields the following line in the creation script:
ALTER TABLE [dbo].[TableName]
  ADD  DEFAULT ((0)) FOR [State]

and the very same thing is being emitted for all the tables but the difference is only reported for one table in the comparison.
How do I address this? How do I know why this table is special and the difference is only reported for this table only?

A: This is an old problem with SSDT that was fixed - now when SSDT imports the model from the database which it uses to generate the list of differences, the wrapping parenthesis are removed and the expression that is left is compared so first of all download the latest SSDT.
I have checked and the problem is in a version 12.0 of SSDT and fixed in 14.0 so the fix is somewhere between there.
I would just set all of your defaults to (( )) - either do it manually or do a compare from your database back to your project, this will do two things firstly it will mean you don't get these annoying additional things and secondly it will make the compare a little bit faster.
If the version stored in the SSDT project doesn't have two ('s and )'s wrapping the expression SSDT goes through an additional step of removing the ('s from the script that is retrieved from the database but if you have (( x )) then SSDT knows that the database will also have (( x )) so it doesn't have to remove the extra brackets.
So, 1 - upgrade, 2 - put them right.
ed


text:
Q: I want to make dropdown in expandable in all time in flutter,
I want to make this dropdown all time expandable state, don't need to un-expandable state. i want to hide or remove un-expandable state in dropdown and i want to show all time expandable to  make true, its possible, is have any idea about it, please add it.
for exapmple, user click the dropdown right icon, don;t need to hide the dropdown items. how to do this

A: to achieve that design you can made a custom design for it. from what you explain the result should be done like this

and here is the custom code that I've created
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
final fieldText = TextEditingController();

MyApp({Key? key}) : super(key: key);

void clearText() {
    fieldText.clear();
}

@override
Widget build(BuildContext context) {
    return MaterialApp(
    home: Scaffold(body: SafeArea(child: ListviewWithCheckBox()))
    );
}
}

class ListviewWithCheckBox extends StatefulWidget {
  @override
  _ListviewWithCheckBoxState createState() => _ListviewWithCheckBoxState();
}

class _ListviewWithCheckBoxState extends State<ListviewWithCheckBox> {
  List<String> _texts = [
    "T-701 - ZONE 1/2/3",
    "Slide Valves on 1st deck",
    "F-301 - South side",
    "Regen - 13th floor",
  ];

  late List<bool> _isChecked;

  @override
  void initState() {
    super.initState();
    _isChecked = List<bool>.filled(_texts.length, false);
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: [
          CheckboxListTile(
            controlAffinity: ListTileControlAffinity.leading,
            title: Text('Oil_and_gas'),
            value: false,
            onChanged: (val) {
              setState(
                () {
                  // ....
                },
              );
            },
          ),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 30.0),
            child: ListView.builder(
              shrinkWrap: true,
              primary: false,
              itemCount: _texts.length,
              itemBuilder: (context, index) {
                return CheckboxListTile(
                  controlAffinity: ListTileControlAffinity.leading,
                  title: Text(_texts[index]),
                  value: _isChecked[index],
                  onChanged: (val) {
                    setState(
                      () {
                        // .....
                      },
                    );
                  },
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

that should work like a charm now


text:
Q: Issue in UIActivityIndicatorView in iPhone? Currently i am working in iphone app, Using UIWebView (Webpage shown in presentModelViewController) to show webpage on the screen, then i add UIActivityIndicatorView to show in load url request, but the UIActivityIndicatorView didn't show in the screen, i tried my level best, please help me.
Thanks in Advance
I tried this:
- (void)viewDidLoad
{
    [super viewDidLoad];

    activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activity.frame=CGRectMake(140, 240, 40, 40);
    [self.view addSubview:activity];

    web = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
    web.delegate=self;
    web.backgroundColor=[UIColor clearColor];
    NSURL *url = [NSURL URLWithString:@"http://wrwr.rww.com/erqrrq"];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];
    [web loadRequest:req];
    [self.view addSubview:web];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [activity stopAnimating];
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [activity startAnimating];
}

A: adding your activitiy indicatore View in to your webView like this:-
 - (void)viewDidLoad
 {
[super viewDidLoad];

activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
activity.frame=CGRectMake(140, 240, 40, 40);

web = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
web.delegate=self;
web.backgroundColor=[UIColor clearColor];
NSURL *url = [NSURL URLWithString:@"http://wrwr.rww.com/erqrrq"];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[web loadRequest:req];
[web addSubview:activity];
[self.view addSubview:web];
}

 - (void)webViewDidFinishLoad:(UIWebView *)webView
{
[activity stopAnimating];
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
[activity startAnimating];
}

A: Try This,
- (void)viewDidLoad
{
    [super viewDidLoad];

    web = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
    web.delegate=self;
    web.backgroundColor=[UIColor clearColor];
    NSURL *url = [NSURL URLWithString:@"http://wrwr.rww.com/erqrrq"];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];
    [web loadRequest:req];
    [self.view addSubview:web];

    activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activity.frame=CGRectMake(140, 240, 40, 40);
    [self.view addSubview:activity];
    [self.view bringSubviewToFront:activity];
}

A: Define UIActivityIndicatorView after defining UIWebView.
  - (void)viewDidLoad
    {
        [super viewDidLoad];

        web = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
        web.delegate=self;
        web.backgroundColor=[UIColor clearColor];
        NSURL *url = [NSURL URLWithString:@"http://wrwr.rww.com/erqrrq"];
        NSURLRequest *req = [NSURLRequest requestWithURL:url];
        [web loadRequest:req];
        [self.view addSubview:web];

     activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        activity.frame=CGRectMake(140, 240, 40, 40);
        [self.view addSubview:activity];
    }

A: The order you add the sub views to the super view is significant. The UIActivityIndicatorView gets added and then the UIWebView overlays it. If you add the UIWebView first, i.e
[self.view addSubview:web];
[self.view addSubview:activity];

the UIActivityIndicatorView will overlay the UIWebView.