text:
Q: JavaScript: difference between a statement and an expression? I asked this question earlier, and after thinking about the topic some more, I began to wonder where the seemingly fuzzy boundary between the meanings of the terms "statement" and "expression" lies. Are all statements also expressions?  Where do the return values in a REPL console come from? They don't always seem to make any intuitive sense.  Of course, if you type 1+1, you'll get 2, but other times it isn't as obvious what the logic is.
Given that anything typed into REPL produces some value, does it mean that it can be used in JS source code as both an expression and a standalone statement?
Can the string of code that could be used for _X_ in the following snippet also be used for _Y_ and vice versa? if(_X_) _Y_?

A: All programs in JavaScript are made of statements and they end with semicolons, except block statements which is used to group zero or more statements. Statements are just perform some actions but do not produce any value or output whereas expressions return some value. When interpreter sees an expression it retrieves its value and replaces expression with new value. Statements are used to manipulate those expressions. You can check whether it's an expresion or a statement here : JavaScript Parser

A: Go to browser console ( Ctrl + Shift + I or Command + Shift + I ) :
Enter code which is ambiguous to you.
If the browser returns undefined after each line of execution, its a statement (except expressions which actually return undefined as a result)
If the browser returns any value other than undefined after each line of execution, its an expression.

The browser console acts as though it uses console.log(statement) for every line of code entered. Refer this for more info.
This procedure is only to verify.
But its necessary to understand:

*

*Expressions return value, statements do not.

*All expressions are statements, but not otherwise. You cannot use a statement in place of an expression.

A:
Are all statements also expressions?

"Wherever JavaScript expects a statement, you can also write an expression. Such a statement is called an expression statement. The reverse does not hold: you cannot write a statement where JavaScript expects an expression. For example, an if statement cannot become the argument of a function."
This is comes from a recent post by Axel Rauschmayer about this topic:
Expressions versus statements in JavaScript
Hope it helps.

A: According to MDN:

An expression is any valid unit of code that resolves to a value.

As such, anything that can be used as an rvalue is an expression.
The criterion is not whether side effects exist. Expressions can definitely have side effects. E.g. a=2 is an expression as it has a value (2) and also assigns a value to a variable. Which is why you can do things like:
let a;
let b = 1 + (a = 2); // a is now 2 and b is 3

It is possible for the same (textual) block of code to be considered both an expression and a statement depending on the context. E.g. the text snippet function f(){} is an expression on line 1 and a statement in line 2 in the below code:
let g = function f() {};
function f() {};

So whether something is an expression or a statement cannot (in the general case) be determined by looking at a textual piece of code out of context; rather it is a property of a node in a syntax tree and can be decided only after the code is (mentally or actually) parsed.
Also, and perhaps more importantly, function statements (a.k.a function declarations) inside a function f form part of the execution context that gets created when function f is invoked. However, function expressions do not form part of that execution context.
One often quoted effect of that is that function declarations get "hoisted" whereas function expressions do not.
A more subtle effect can also be experimentally observed in deep recursions given that function statements take up space in the execution context whereas function expressions do not. E.g. the below code uses infinite recursion of a function f. Function f in the first case includes a function expression inside it, in the second case it includes the equivalent function declaration:
// Function Expression
{
    let i = 0;
    try {

        function f () {
            i++;
            (function g() {})(); // this is an expression
            f();
        }

        f();

    } catch (err) {
        console.log(`Function Expressions case: depth of ${i} reached. Error: ${err.name}`);
    }
}
// Function Declaration
{
    let i = 0;
    try {
        function f () {
            i++;
            function g() {}; // this is a statement
            g();
            f();
        }

        f();

    } catch (err) {
        console.log(`Functions Declarations case: depth of ${i} reached. Error: ${err.name}`);
    }
}

On my machine I consistently get the following (in node.js):
Function Expressions case: depth of 17687 reached. Error: RangeError
Functions Declarations case: depth of 15476 reached. Error: RangeError

… which is consistent with the fact that Function Declarations increase the amount of space necessary to hold an execution context and thus eat up stack space a little faster and so slightly decrease the maximum recursion depth.

A: I highly recommend reading Dr. Axel Rauschmayer's comprehensive blog post
Expressions versus statements in JavaScript
as mentioned in @ZER0's accepted answer above.
But my favorite memory shortcut is:

Expression:
e can be set Equal to an Expression
  ..orExpressed by printing it.
  Statement:
  ..anything else.

The following is modified from
Anders Kaseorg's Quora answer.
A statement is a complete line of code that performs some action.
Every Expression can be used as a statement
(whose effect is to evaluate the expression, and ignore the resulting value).
But an Expression is any section of the code that evaluates to a value.

Expressions can be combined "horizontally" into larger expressions using operators.
E has a horizontally flat top

Most statements cannot be used as expressions.

Statements can only be combined "vertically" by writing one after another, or with block constructs.
S runs vertically in comparison.

From Quora Post by Ryan Lam:

Here's a general rule of thumb: If you can print it, or assign it to a variable, it's an expression. If you can't, it's a statement.

Here are some examples of expressions:
2 + 2
3 * 7
1 + 2 + 3 * (8 ** 9) - sqrt(4.0)
min(2, 22)
max(3, 94)
round(81.5)
"foo"
"bar"
"foo" + "bar"
None
True
False
2
3
4.0

All of the above can be printed or assigned to a variable.
Here are some examples of statements:
if CONDITION:
elif CONDITION:
else:
for VARIABLE in SEQUENCE:
while CONDITION:
try:
except EXCEPTION as e:
class MYCLASS:
def MYFUNCTION():
return SOMETHING
raise SOMETHING
with SOMETHING:

None of the above constructs can be assigned to a variable. They are syntactic elements that serve a purpose, but do not themselves have any intrinsic "value". In other words, these constructs don't "evaluate" to anything. Trying to do any of the following, for example, would be absurd, and simply wouldn't work:
x = if CONDITION:
y = while CONDITION:
z = return 42
foo = for i in range(10):

A: At its simplest terms, expressions are evaluated to produce a value. On the other hand, statements are executed to make something happen.

A: Expression produces or evaluates some value.
Examples of expressions:
new Date() produces new Date object without any side effect.
[1,2,3] produces a new array without any side effect.
5+6 produces a new value 11.It just produces new value without any side effect.
Statement produces some behavior or does something and it has some side effect also.
Based on the side effect, statements can be categorized.
x=5; is a statement and here side effect is assignment or change in x.
setTimeout() - start of timer is the side effect.
Statements are generally separated by semicolon.
Expression statement are the expression that has some side effect or simply "expression with side effect".
Examples of expression statement:
x+=6; is the complex expression(group of primary expressions) is doing assignment that is a side effect, so called expression statement.
delete a[2];

A: Expression: a unit of code that resolves to a value, as instance, literals & operators. Examples for expressions:
> 3
> 1 + 2
> "expression"
> fn()
> []
> {}

Statement: a unit of code representing one instruction or more, usually starts with a language reserved keyword and ends, explicitly or implicitly, with a statement terminator. Examples of statements:
> 3;
> let x = 3;
> if () {}
> for () {}
> while () {}

A: In short, expression is value, statement is behavior.
Let me just show you some naive examples.
The following code define a value. It is a statement called let statement led by let keyword. Here 1 is an expression.
// statement
// |---------|
   let n = 1 ;
//        |-|
//        expression

And this is for statement led by for keyword. It comes with some nested expressions and statements.
//      expression(1)
//      |-----------|
   for (num in numArr) {                 //--+
                                         //  |
      sum += (num * 3); // statement(2)  //  |
//            |-----|                    //  |statement(1)
//            expression(2)              //  |
                                         //  |
   }                                     //--+

So a statement is an instruction unit telling computer what to DO. for statement, while statement, if statement, they are all actions, in another word tasks, or behaviors.
But for expression, we are talking about values, valuables, objects, or some procedures that can produce a value, like function.
1 + 2
(2 + 3) * 5 === 25
new Foo()

So Javascript also has function expression. Because function is a value. In the following code,

*

*The entire snippet is a statement.

*Everything after = is an expression.

*return width * height; is nested statement.

*width * height is an expression.

const rectArea = function(width, height) {
  return width * height;
};

A: We have the following two types of expressions:
1. Boolean expression is uses to execute block of statements.

2. Arithmetic expression is uses for variable assignments, which acts as a statements too.
For example: number = number + 1;

A: A fragment of code that produces a value is called an expression. Every value that is written literally (such as 22 or "psychoanalysis") is an expression. An expression between parentheses is also an expression, as is a binary operator applied to two expressions or a unary operator applied to one.
An expression corresponds to a sentence fragment in human language, a JavaScript statement corresponds to a full sentence. A program is a list of statements.
The simplest kind of statement is an expression with a semicolon after it. This is a program:
1;
!false;
It is a useless program, though. An expression can be content to just produce a value, which can then be used by the enclosing code. A statement stands on its own, so it amounts to something only if it affects the world.
Statement could have side effects.
https://eloquentjavascript.net/02_program_structure.html


text:
Q: How to get this Json format I want the following JSON format for my application
([{
  "CUSTOMERID":null,
  "STORENUMBER":null,
  "CUSTOMERNAME":"name",
  "ADDRESS1":" Hyderabad",
  "ADDRESS2":null,
  "CITY":"Sec",
  "STATE":"TR"
}]);

But when I use json_encode for my array I get the below format
[{
  "CUSTOMERID":null,
  "STORENUMBER":null,
  "CUSTOMERNAME":"name",
  "ADDRESS1":" Hyderabad",
  "ADDRESS2":null,
  "CITY":"Sec",
  "STATE":"TR"
}]

I miss the starting ( and ending ); .

A: echo '('.json_encode($data).');';

redpajama_set_name: RedPajamaStackExchange


text:
Q: Increment the value if it exists, else add a new entry in DynamoDB I have a DynamoDB table with columns and primary key as ipAddress:

*

*ipAddress

*visits

I am fetching the IP address of the user from my react website and inserting it to DynamoDB via a Lambda function and API Gateway POST request.
If the IP address coming from the React website is already present in the DynamoDB, then increment the value in visits column. If not, then create a new record with the new IP address and visits = 1. I tried using ConditionExpression but to no avail.
So far, I am only inserting the ipAddress using Lambda. Below is my Lambda function in NodeJS:
const AWS = require("aws-sdk");
const documentClient = new AWS.DynamoDB.DocumentClient();

exports.handler = async event => {
  const { ipAddress} = JSON.parse(event.body);
  const params = {
    TableName: "ipAddress",
    Item: {
      ipAddress: ipAddress,
    }
  };

  try {
    const data = await documentClient.put(params).promise();
    const response = {
      statusCode: 200,
    };
    return response;
  }
  catch (e) {
    return {
      statusCode: 500,
      body: JSON.stringify(e)
    };
  }

};

A: We need to use update-item rather than put-item, both creates a record if record doesn't exist. But update-item accepts UpdateExpression to help us update an existing attribute.
UpdateExpression: "SET visits = if_not_exists(visits, :initial) + :num"
if_not_exists helps to use initial value for the first time when attributes visits doesn't exist.
docClient.update(
  {
    TableName: "ipAddress",
    Key: {
      ipAddress: ipAddress,
    },
    UpdateExpression: "SET visits = if_not_exists(visits, :initial) + :num",
    ExpressionAttributeValues: {
      ":num": 1,
      ":initial": 0,
    },
  },
  function (error, result) {
    console.log("error", error, "result", result);
  }
);


text:
Q: Automating uploading files via asking filepath from user in python # This module takes path of any random dataset from the user

class User_Input():
  # Taking File Path as input from the user
  user_input = input("Enter the path of your file: ")

  # The assert keyword lets you test if a condition in your code returns True, if not, the program will raise an AssertionError.
  assert os.path.exists(user_input), " did not find the file at, "+str(user_input)
  user_file = open(user_input,'r+')

  print(" found the file !")

  for fp in user_file:
      # Split the extension from the path and normalise it to lowercase.
      ext = os.path.splitext(fp)[-1].lower().suffix()

      # For handling breakdown in case of any errors
      try:
        # Now we can simply use .endswith to check for equality, no need for wildcards.
        # For handling csv files
        if ext.endswith('.csv'):
            df = pd.read_csv(user_input)

        # For handling excel files
        elif ext.endswith('.xlsx'):
            df = pd.read_excel(user_input)

        # For handling json files
        elif ext.endswith('.json'):
            df = pd.read_json(user_input)

        # For handing unknown files types
        else:
            print( fp,"is an unknown file format.")
            break

      # to handle the situation if try block gets failed
      except:
          pass

  user_file.close()

I am trying to automate uploading any file extension(like- .csv, .json, .xlsx etc) and read the code in dataframe. But , this shows assertion error, but I am providing the right path? Also there is some problem with the encoding!
It must not break and tell the user about any errors!

A: The Assertion error is raised by your assert statement, which is outside the try block so the error raised is not caught by the except statement.
A better alternative may be to remove the assert altogether and open the file within the try block:
try:
    with open(user_input, "r+") as file:
           # process file contents
except:
    pass

If the path is invalid, a FileNotFound error will be raised safely in the try block.


text:
Q: Mounting share Problems Ubuntu running on Windows 10 in VMWare I have an Ubuntu 20.04.3 LTS running in VMWare Workstation 15 Pro on a Windows 10.
In that Ubuntu I have a Plex Server running.
I use vmhgfs-fuse in the fstab to mount the shared folders to certain points and that has been working fine for some time now.
But lately I'm having troubles with the mounts. I've noticed that after a reboot of the VM at least one folder is not mounted correctly.
When I show the list of mounted folders I get:
ls cannot access '<folder-name_1>' : Input/output error
or
ls: cannot access '<folder-name_1>': Transport endpoint is not connected
I have a file for every folder to remount. When I do that for the folder that isn't mounted correctly I get:
fusermount: failed to unmount <folder-path>: Invalid argument
Error -107 cannot open connection!
Though after a few tries the errors disappear and it will remount. To check I list the folders and their contents again.
Sure enough the folder(s) in question is/are mounted again.
But, then a different, already mounted folder at boot, will go nuts and I get the same message with "Input/output error" or "Transport endpoint ..." for that one or even two.
That goes on and on and on and on, until eventually maybe I have all of them mounted without problems or I just give up and leave the least relevant one(s) unmounted.
Does anybody have an idea why this could be happening?
I can't say when it started, but I believe it might have something to do with the amount of folders I'm sharing/mounting. Started out with maybe 5 and now there's 11. Had 13 of them but removed 2 in hope that it would solve the problem.
Thanks


text:
Q: WAMP MongoDB - PHP extension I have a problem with installation of MongoDB extension to PHP in WAMP SERVER.
The error that I obtain is show in photo

A: For the latest versions, we have to be careful about thread-safe version of the dll file too.
You can download latest dll from this link.
https://pecl.php.net/package/mongodb

And in this link, you have thread-safe and and non-thread-safe versions of .dll file.

if you have php7ts.dll or ts.dll file in your PHP installed directory you need to download that thread-safe dll file.

And after download you can add dll file to \wamp\bin\php\php{version}\ext directory and call inside php.ini file
extension=php_mongodb.dll

A: That is telling you that you have not added the following line to the correct php.ini file
Use
wampmanager -> PHP -> php.ini

to edit the CORRECT php.ini file.
Add your
extension=php_mongo.dll

with the other extension lines
If you have an extension line set in the correct php.ini file, then you need to ensure that the DLL with the same name is in the \wamp\bin\php\php{version}\ext folder

A: One other piece of information on this:

*

*After you do "add extension=mongodb in bin->apache->apache(version)->bin->php.ini", you have to exit wampserver (right click the systray icon an choose exit) and restart it for it to "see" your change in the apache php file. Simply stopping and starting all services from the left click menu of wampserver does not refresh this new setting.

A: add extension=mongodb  in bin->apache->apache(version)->bin->php.ini


text:
Q: Is there an R function to draw a solid circle with a radius in user coordinates Is it possible to draw real solid circle with a radius in "user" coordinates?
I tried the following:
Polygons:
I don't want to use them because I need real circles in the resulting svg.
Segments
segments(x, y, x, y, lwd=px, lend=0)

With segments there is the problem that I don't find a way to specify the segment in "user" coordinates.
The resulting graph is at the end exported to PDF.
Update
I draw a graph with a lot of elements and the elements has a distinct width. The width of the elements depends on the width at the x-axis. If I don't use user coordinates the result in the PDF is not correct in dependence to the x-axis.
A Polygon is an approximation to a circle and if I use them the result e.g. PDF is very large and the performance is not good and memory usage is very high. I draw 10,000 circles and more on one graph.
I use the following code with the described performance problems:
circle <- function(x, y, r, col) {
  edgeCount <- 50
  intervals <- (1:edgeCount) / edgeCount * 2 * pi
  for(i in 1:length(x)) {
    polygon(r[i]*sin(intervals) + x[i], r[i]*cos(intervals) + y[i], col=col[i],border=NA)
  }
}

A: If you're comfortable with using a wrapper for sp's SpatialLine object you can try the oceanmap package which has a quite useful function called SpatialCircle(). It essentially builds a circle via seq() and adjusts it for your center point coordinates x and y, and for your radius r. It's still a set of line segments (so not one curved line), but quite simple to use.
Result:

Code:
Pretty straightforward:
# Load libraries.
library(oceanmap)

# Generate plot window and data.
set.seed(1702)
plot.new()
plot.window(xlim = c(0, 20), ylim = c(0, 10),
            asp = 1, xaxs = "i",  yaxs = "i")
axis(1)
axis(2)
box()

n <- 1000
x <- runif(n, 0, 20)
y <- runif(n, 0, 10)

for (i in 1:n) {

    circle <- SpatialCircle(x = x[i], y = y[i], r = 0.1, n = 1000)
    lines(circle)

}

This also works with ggplot2 with some data wrangling.

Addendum: Precision of SpatialCircles
If you want to check out what n (precision) in the SpatialCircle() function really means, try the following:
nrow(circle@lines[[1]]@Lines[[1]]@coords)

Result:

[1] 1000

This means that the object has 1,000 coordinate pairs (x and y) through which a line can be drawn. Furthermore, this line will have 999 distinct line segments, as the first and the last coordinate pairs are always identical. Proof:
all.equal(circle@lines[[1]]@Lines[[1]]@coords[1, ],
          circle@lines[[1]]@Lines[[1]]@coords[1000, ])

Result:

[1] TRUE

A: If found a solution myself with the help of Gregor2 which did lead me to the library "grid".
library(grid)
#draw frame using normal plot
plot(0, 0, cex=0)

margins <- par("mar")

#1: bottom 2:left 3:top 4:right
mb <- unit(margins[1], "lines")
ml <- unit(margins[2], "lines")

mt <- unit(margins[3], "lines")
mr <- unit(margins[4], "lines")

#create viewport equivalent to margins in par
pushViewport(viewport(x = ml, y = mb, width = unit(1, "npc") - ml - mr, height = unit(1, "npc") - mb - mt, just=c("left", "bottom"), clip=TRUE))

#draw circle in npc units (easily convertable to user units using grconvertX)
grid.draw(circleGrob(x=0.5, y=0.5, r=0.5, default.units="npc", gp=gpar(col="blue", fill="blue")))

popViewport()


text:
Q: Writing a mini-language with haskell, trouble with "while" statements and blocks { } EDIT: problem partially solved, skip to the bottom for update.
I'm writing a small language using haskell, and I've made a lot of progress, but I am having trouble implementing statements that use blocks, like "{ ... }".  I've implemented support for If statements like so in my parser file:
stmt = skip +++ ifstmt +++ assignment +++ whilestmt

ifstmt = symbol "if" >>
         parens expr >>= \c ->
         stmt >>= \t ->
         symbol "else" >>
         stmt >>= \e ->
         return $ If c t e

whilestmt = symbol "while" >>
            parens expr >>= \c ->
        symbol "\n" >>
        symbol "{" >>
        stmt >>= \t ->
        symbol "}" >>
        return $ While c t

expr = composite +++ atomic

And in the Syntax file:
class PP a where
  pp :: Int -> a -> String

instance PP Stmt where
  pp ind (If c t e) = indent ind ++
                      "if (" ++ show c ++ ") \n" ++
                      pp (ind + 2) t ++
                      indent ind ++ "else\n" ++
                      pp (ind + 2) e
  pp ind (While c t) = indent ind ++
                   "while (" ++ show c ++") \n" ++
                   "{" ++ pp (ind + 2) t ++ "}" ++
                   indent ind

Something is wrong with the while statement, and I don't understand what. The logic seems correct, but when I run the code I get the following error:
EDIT: Fixed the first problem based on the first reply, now it is not recognizing my while statment which I assume comes from this:
exec :: Env -> Stmt -> Env
exec env (If c t e) =
    exec env ( if eval env c == BoolLit True then t else e )
exec env (While c t) =
    exec env ( if eval env c == BoolLit True then t )

The file being read from looks like this:
x = 1; c = 0;
if (x < 2) c = c + 1; else ;
-- SEPARATE FILES FOR EACH
x = 1; c = 1;
while (x < 10)
{
  c = c * x;
  x = x + 1;
}
c

I've tried to understand the error report but nothing I've tried solves the problem.

A: >> and >>= bind tighter than $. Try using
return (While c t)

instead of
return $ While c t

And also, put parenthesis around the lambda expression on the right hand side of >>=.
Or just use do-notation:
whilestmt = do
    symbol "while"
    c <- parens expr
    symbol "\n"
    symbol "{"
    t <- stmt
    symbol "}"
    return $ While c t

A: The problem is that in Haskell, an if statement always has to have an else in addition to a then.  Your implementation of exec for While specifies what to do when the condition is True, but says nothing about the behavior when the condition is False.  In fact, your code only executes the body of the while loop once when the condition is True, but it should keep executing it (and threading the updates to the environment) until the condition becomes False.  So, something like this:
exec env (While c t) = execWhile env c t

execWhile env c t | eval env c == BoolLit True = let env' = exec t in execWhile env' c t
                  | otherwise = env


text:
Q: Encrypted FTP Storage I guess this is kind of a programming question, because I'm going to write a program if this doesn't exist.
So I found a very cheap web-host (I don't really care about the actual web hosting). They will give me a domain name and ftp server with a ton of storage space. Anyway, I want to backup a few hundred gigs of data (mostly family photos and scans of important documents). I also want to backup any future family photos / documents. I don't care if everything on my local NAS dies in a fire, I just want to have the photos and important documents backed up off-site.
So I want some program that lets me select folders locally and schedules them to be backed up to the ftp server. I'm a bit of a security nut, so i'd like the files to be encrypted locally before being transferred up onto the server.
I know I can do this with truecrypt volumes, but I don't want to transfer an entire encrypted volume blob up to the server ever time I change a file in it. So I could do multiple true crypt volumes but that will be a pain to manage
Also this must be mac/linux compatible although I'll primarily be on linux.
I basically need rsync + truecrypt + cron + sftp all rolled into a cryptographically secure program.
I've been searching for days with no luck. Any ideas?

A: mozyBackup does this - it doesn't use FTP, it has a custom uploader.
ps. Remember a typical home ADSL connection only does about 1Gb/day upstream
Linux option.
Out of the box option probably duplicity ( for example see http://www.howtoforge.com/creating-encrypted-ftp-backups-with-duplicity-and-ftplicity-on-debian-lenny )
Otherwise if these are basically rarely changed archive copies of files - I would roll my own gnupg (or dpad) individual file encryption, a file changed script, and ftp or rsync.


text:
Q: How to solve surface area problem? A sphere balloon is inflated at 5 cubic centimeters per second. How fast is the surface area increasing when the radius is 25 centimeters?
I don't understand the goal of the problem. I thought related rate problems were supposed to be solved through differentiation, but there's nothing in the problem to differentiate. How can it be solved?

A: You are looking for $\frac{dA}{dt}=\frac{dA}{dr}\cdot  \frac{dr}{dV}\cdot  \frac{dV}{dt}$
The volume is $V(r)=\frac{4}{3}\pi \cdot r^3$. Differentiating $V(r)$ w.r.t $r$.
$\frac{dV}{dr}=4\pi r^2$. This is equal to the surface of the balloon (A).
$A=\frac{dV}{dr}\Rightarrow \frac1A=\frac{dr}{dV}\Rightarrow \frac1{4\pi r^2}=\frac{dr}{dV}$
And $\frac{dA}{dr}=8\pi r$
Therefore $\frac{dA}{dr}\cdot \frac{dr}{dV}=\frac{8\pi r}{4\pi r^2}=\frac2r$
The values of $\frac{dV}{dt}$ and $r$ are given.

A: hint...You are looking for $\frac {dA}{dt}$ when $r=25$. For the sphere, $V=\frac 43\pi r^3$ and $A=4\pi r^2$. You are given $\frac{dV}{dt}=5$.
Therefore using the Chain Rule,$$\frac{dA}{dt}=\frac{dA}{dr}\times \frac{dr}{dV}\times \frac{dV}{dt}$$


text:
Q: Make linux kernel function show in ftrace available_filter_function I want to trace perf_event_open using ftrace but it does not show in available_filter_function. In fact, it seems that only functions loaded in modules are shown.
Is there a default blacklist for non-module functions? how to add the function I need?

A: There is some info in "Secrets of the Ftrace function tracer" article, January 20, 2010 by Steven Rostedt: https://lwn.net/Articles/370423/

A list of functions that can be added to the filter files is shown in the available_filter_functions file. This list of functions was derived from the list of stored mcount callers previously mentioned.

Set of functions listed in the file depends on kernel compilation options (please check them in /boot/config* or in /proc/config.gz and add result to the question):
CONFIG_FUNCTION_TRACER
CONFIG_DYNAMIC_FTRACE
CONFIG_FUNCTION_GRAPH_TRACER

There is more info about mcount in earlier article of series: https://lwn.net/Articles/365835/ Debugging the kernel using Ftrace - part 1, December 2009, Steven Rostedt:

One of the most powerful tracers of Ftrace is the function tracer. It uses the -pg option of gcc to have every function in the kernel call a special function "mcount()" .. When CONFIG_DYNAMIC_FTRACE is configured the call is converted to a NOP at boot time to keep the system running at 100% performance. During compilation the mcount() call-sites are recorded.

Can you also check files in  /sys/kernel/debug/tracing/events/syscalls/sys_enter_perf_event_open/ ?
Syscalls are available to ftrace not as functions, but as events (example from opensourceforu.com/2010/12/kernel-tracing-with-ftrace-part-2/):
trace-cmd record -e syscalls ls  ##Initiate tracing on the syscall 'ls'
##(A file called trace.dat gets created in the current directory.)
trace-cmd report                 ## displays the report from trace.dat

For me trace-cmd record -e syscalls perf stat ls -d . catches calls to perf_event_open.


text:
Q: How can I pass more parameters to a custom sort() function? I have an array of objects I need to sort on a custom function. Since I want to do this several times on several object attributes, I'd like to pass the key name for the attribute dynamically into the custom sort function:
function compareOnOneFixedKey(a, b) {
    a = parseInt(a.oneFixedKey)
    b = parseInt(b.oneFixedKey)
    if (a < b) return -1
    if (a > b) return 1
        return 0
}

arrayOfObjects.sort(compareByThisKey)

This should become something like:
function compareOnKey(key, a, b) {
    a = parseInt(a[key])
    b = parseInt(b[key])
    if (a < b) return -1
    if (a > b) return 1
        return 0
}
arrayOfObjects.sort(compareOn('myKey'))

Can this be done in a convenient way?

A: Yes, have the comparator returned from a generator which takes a param which is the key you want
function compareByProperty(key) {
    return function (a, b) {
        a = parseInt(a[key], 10);
        b = parseInt(b[key], 10);
        if (a < b) return -1;
        if (a > b) return 1;
        return 0;
    };
}
arrayOfObjects.sort(compareByProperty('myKey'));

compareByProperty('myKey') returns the function to do the comparing, which is then passed into .sort

A: You may add a wrapper:
function compareOnKey(key) {
    return function(a, b) {
        a = parseInt(a[key], 10);
        b = parseInt(b[key], 10);
        if (a < b) return -1;
        if (a > b) return 1;
        return 0;
    };
}

arrayOfObjects.sort(compareOnKey("myKey"));

A: You would need to partially apply the function, e.g. using bind:
arrayOfObjects.sort(compareOn.bind(null, 'myKey'));

Or you just make compareOn return the actual sort function, parametrized with the arguments of the outer function (as demonstrated by the others).

A:

const objArr = [{
    name: 'Z',
    age: 0
  }, {
    name: 'A',
    age: 25
  }, {
    name: 'F',
    age: 5
}]

const sortKey = {
    name: 'name',
    age: 'age'
}

const sortArr = (arr, key) => {
    return arr.sort((a, b) => {
        return a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0
    })
}

console.log("sortKey.name: ", sortArr(objArr, sortKey.name))
console.log("sortKey.age: ", sortArr(objArr, sortKey.age))


text:
Q: Executing python script with cron job from MacOS I am trying to create a very simple Cron job on MacOS to execute a Python script.
My Cron job :
* * * * * usr/bin/python3 /Users/gaetan/Desktop/createfolder.py

When I run the script from the terminal is working fine but from cron is not doing anything.
I don't understand what could be the error, I have given all the rights and double check the path.

A: on Mac and linux, the crontab syntax is same!
But i suggest not to manipulate your crontab with default system for some reason.
As you are using python You can use celery It will save your huge time schedule task: https://docs.celeryproject.org/en/stable/userguide/periodic-tasks.html

A: You can absolutely use cron on macOS. First step grant the binary permissions over your full disk.

Second, be sure you check for a full path to everything - your python executable is not correct in the question as it needs to start with /usr/...
Here is an answer on a partner site specific to Apple operating systems with details on debugging and privacy controls if you'd like more help.


text:
Q: text centering on CSS with flexbox I'm learning flex box and can not get my text to center align.
I am aware I can center align vertically using padding, but I want it to be more of an automatic centering and not edit each item every time.
Although this link did help, it was not what I was looking for.
I need to get my .item to center horizontally and vertically with the minimum amount of code.
CodePen

.parent {
  display: flex;
  flex-direction: row-reverse;
  justify-content: space-around;
  flex-wrap: wrap;
}
.item {
  color: white;
  margin: 0px;
  width: auto;
  height: 200px;
  background-color: blue
}

 Display: flex

If you wanna

Then you gotta

Go findz it

A: you need to add align-items:center and a new display:flex to the child

body {
  margin: 0
}
.parent {
  display: flex;
  flex-direction: row-reverse;
  justify-content: space-around;
  flex-wrap: wrap;
  border: black solid;
  color: white
}
.item {
  display: flex;
  align-items: center;
  height: 200px;
  background: lightgreen;
}

 Display: flex

If you wanna

Then you gotta

Go findz it

A: To center .item children within .parent, use the following code:
<!DOCTYPE html>

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

 Display: flex

If you wanna

Then you gotta

Go findz it


text: Q: What is the difference between RealModelType and ModelType on ModelBindingContext? I'm currently working on writing a custom model binder which handles a variety of different object types, and we're looking for the best way to determine type of the incoming object. However, on ModelBindingContext we have both ModelType and RealModelType, and googling hasn't found anything that tells me what exactly is the difference between the two.


text:
Q: Implementing a search feature for multiple websites, is Apache Solr a good choice? I am currently managing a website where those without any web experience can create their own basic multipage website. The site also offers additional 'widgets' that can be placed onto a site to provide interactive features such as comments etc.
We are looking into adding a search widget where the customer can place a search onto their website and it will search all content within their own website including the other 'widgets' that have been used (The individual page content is basic html and the widgets data for all users is stored in a single database).
For this we have looked into a number of options on how to do the indexing and searching and have came down to the following options: PHP Zend Lucene or Apache Solr.
We feel Zend Lucene will not be able to achieve what we need, mostly because some of these websites are hosted remotely but use widgets loaded through the main website. Also if we used a single index this could potentially have over 300,000 documents indexed and as I hear Zend Lucene is not good for performance.
Apache Solr seems like the preferred choice. However I have some questions regarding the setup of this and 'multiple' sites.

*

*Would it be better to have just a single index and have some unique identifier for each document indexed by a site, then when searching we can use this identifier to restrict to documents from that site.

*Or would it be better to have multiple indexes?

*Or is there a better option that we have overlooked?

I am still open to suggestions at this point of how we can implement this if you think you know of a better approach.

A: Regarding performance, Solr has many of Lucene caching and other optimized parameters. Most people think Zend Lucene is slower than Java Lucene, so your choice might be to use SOLR, but this really depends on the specific application and server resources.
Check this good previous post : Zend_Search_Lucene vs SOLR

A: You might want to look at Apache Nutch, which provides web crawling on top of Lucene's search engine.


text:
Q: Regex to validate entire multiline text in angularjs I need some help.

I have to construct a regex for angularjs ng-pattern attribute.
The regex has to validate a text, not each line or some pieces. The text has to contains some amounts with exactly 2 decimals and each amount should be entered in the new line. Also, spaces are accepted before and after each amount.
If one line contains 2 amount then the entire text is not valid.
For example this text is valid because each amount is entered in the new line:
123.34
12345.56
2.54

This example is not valid because one line contains 2 amounts:
12.43
123.32 2345.54
124.43

This example is not valid because one amount does not contains 2 decimal(each amounts has to be with exactly 2 decimals):
123
123.43
123.65

My best try is ^(([0-9]+[.][0-9]{2})\s*)+$ and it can be tested here. But my regex it's not enough because it accept text with multiple amounts in the same line.
Thanks

A: Regex is not my strong point, so there may be a much simpler way to do this, but this does meet your requirements:
^(([^\S\r\n]*[0-9]+[.][0-9]{2}[^\S\r\n]*)\n)*(([^\S\r\n]*[0-9]+[.][0-9]{2}[^\S\r\n]*))$

Effectively what it does is ensure that the last line (without a newline character at the end) is always present, but also allows for optional lines before that which end with a newline (\n).
We also use the [^\S\r\n] part in place of \s to ensure that it checks for whitespace characters excluding newline, as the newline is what causes an issue with validating multiple values on the same line.
Here is a working example

A: You may use
ng-pattern="/^[^\S\r\n]*\d+\.\d{2}(?:[^\S\r\n]*\r?\n[^\S\r\n]*\d+\.\d{2})*[^\S\r\n]*$/"

See the regex demo.
Or, since angular trims the input before sending it to the regex engine by default (if you have no ng-trim or if you have ng-trim="true"), you may also use
ng-pattern="/^\d+\.\d{2}(?:[^\S\r\n]*\r?\n[^\S\r\n]*\d+\.\d{2})*$/"

Or, if you want to make sure there are no empty lines at start/end, use the first regex with ng-trim="false".
Pattern details

*

*^ - start of string

*[^\S\r\n]* - any 0+ horizontal whitespaces

*\d+ - 1 or more digits

*\. - a . char

*\d{2} - 2 digits

*(?: - start of a non-capturing group matching...

*

*[^\S\r\n]* - any 0+ horizontal whitespaces

*\r?\n - a line break sequence

*[^\S\r\n]*\d+\.\d{2}  - any 0+ horizontal whitespaces, 1+ digits, . and 2 digits

*)* - ... zero or more times

*[^\S\r\n]* - any 0+ horizontal whitespaces

*$ - end of string.

A: the problem is that \s matches also spaces use [\r\n] instead to match newlines and cariage return.
EDIT my first post mentioned \R but it's PCRE specific.
EDIT following comments to accept also space at the end of line
^(([0-9]+[.][0-9]{2}) *(?:\r?\n|$))+$

regex101

A: add the multiline flag /m to be able to anchor ^ to the start of each line
/^([0-9]+[.][0-9]{2})\s*$/gm
e.g. https://regex101.com/r/XMTSok/4


text:
Q: Calling QVector in another class error in Qt I recently have a calling QVector out of index problem.To make my question easy to understand, I created two classes, class A and Class B.
In Class B:
class B
{
public:
    B();

    QVector<int> mVector;
    void setVector()
    {
        mVector.resize(10);
        qDebug() << "size: " << mVector.size();
        for(int i = 0; i < 10; i++) {
            mVector.push_back(i);
        }
        qDebug() << "vector:" << mVector;
    }
};

And I called the function and QVector in Class A:
B testingB;
qDebug() << testingB.mVector.size();
testingB.setVector();
qDebug() << testingB.mVector;
qDebug() << testingB.mVector.size();

Here is the debug outcome:
0
size:  10
vector: QVector(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
QVector(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
20

I noticed after that the QVector has 20 elements, which should have 10. Why would this happen? Thanks.


text:
Q: How to delete letters only when they form a word (i.e &Co.) and not when they are part of an word (Co-nstruction) I have to cleanup a column with Companies names by removing Inc, Ltd, &Co, Co, Corp, . , $, &, etc, and the list can be updated later on.
In Sql server 2016 I used Replace but it will replace everywhere those letters not only when they form a specific word, ex: name Co.
alter table [CompanyList] add CleanLegalName as
    cast (Rtrim( Replace (Replace (Replace (Replace (Replace (Replace (Replace (Replace (REPLACE
        ([Legal Name], ' INC', ''), '.', ''), ' LTD', ''), ' Inc', ''), ' Ltd', ''), ' LIMITED', ''), ' INCOPORATED' ,'') , ',' , '') , ' CO', '')
      ) as varchar(200))

The problem is Replace will replace everywhere these letters, like: 'Jane Construction' with 'Jane nstruction' , 'Inca Food' with 'a Food'. How can I remove these letters only when they form a word by themselves and not as part of other word ?
Thank you

A: Let's say that we have the following scenario
    CREATE TABLE #Temp([Legal Name] NVARCHAR(MAX))

    INSERT INTO #Temp ([Legal Name]) VALUES ('Beer Acme Co.')
    INSERT INTO #Temp ([Legal Name]) VALUES ('Company of Brothers Co')
    INSERT INTO #Temp ([Legal Name]) VALUES ('My Star Inc.')
    INSERT INTO #Temp ([Legal Name]) VALUES ('Incredible Monsters INC')
    INSERT INTO #Temp ([Legal Name]) VALUES ('Limit Is The Sky Ltd')
    INSERT INTO #Temp ([Legal Name]) VALUES ('Limit Is The Universe Ltd.')
    INSERT INTO #Temp ([Legal Name]) VALUES ('Unlimited Minds Limited.')
    INSERT INTO #Temp ([Legal Name]) VALUES ('Unlimited Borders Limited')

I can propose two ways to try help you.
Option 1
Via Scalar-Valued Function
    CREATE FUNCTION [dbo].[GetClearedName](@VALUE NVARCHAR(MAX))
    RETURNS NVARCHAR(MAX)
    AS
        BEGIN

            DECLARE @PATTERN NVARCHAR(MAX)
            DECLARE @TEMP TABLE ([PATTERN] NVARCHAR(MAX))

            INSERT INTO @TEMP ([PATTERN]) VALUES ('%Co.')
            INSERT INTO @TEMP ([PATTERN]) VALUES ('% Co%')
            INSERT INTO @TEMP ([PATTERN]) VALUES ('%Inc.')
            INSERT INTO @TEMP ([PATTERN]) VALUES ('% Inc')
            INSERT INTO @TEMP ([PATTERN]) VALUES ('% Ltd')
            INSERT INTO @TEMP ([PATTERN]) VALUES ('%Ltd.')
            INSERT INTO @TEMP ([PATTERN]) VALUES ('%Limited.')
            INSERT INTO @TEMP ([PATTERN]) VALUES ('% Limited')

            DECLARE @RESULT NVARCHAR(MAX)

            SET @RESULT = @VALUE

            DECLARE PATTERN_CURSOR CURSOR FOR SELECT [PATTERN] FROM @TEMP

            OPEN PATTERN_CURSOR
            FETCH NEXT FROM PATTERN_CURSOR INTO @PATTERN

            WHILE (@@FETCH_STATUS = 0)
                BEGIN

                    IF (PATINDEX(@PATTERN, @RESULT) > 0)
                        BEGIN
                            SET @RESULT = SUBSTRING(@RESULT, 0, PATINDEX(@PATTERN, @RESULT))
                        END

                    FETCH NEXT FROM PATTERN_CURSOR INTO @PATTERN
                END

            CLOSE PATTERN_CURSOR
            DEALLOCATE PATTERN_CURSOR

            IF (LEN(@RESULT) <> 0)
                RETURN @RESULT

            Return @VALUE
        END

You can use the function that way:
    SELECT [dbo].[GetClearedName]([Legal Name]) FROM #Temp

    DROP TABLE #Temp

Option 2
Using #SQL, also this can be converted into a function.
    SELECT [Legal Name],
        SQL#.RegEx_Replace4k(
            SQL#.RegEx_Replace4k(
                SQL#.RegEx_Replace4k(
                    SQL#.RegEx_Replace4k([Legal Name], N'(CO+\.|\sCO$)', N' ', -1, 1, 'IgnoreCase'),
                                                            N'(INC+\.|\sINC$)', N' ', -1, 1, 'IgnoreCase'),
                                                                    N'(LTD+\.|\sLTD$)', N' ', -1, 1, 'IgnoreCase'),
                                                                        N'(Limited+\.|\sLimited$)', N' ', -1, 1, 'IgnoreCase')
        As [Cleared Name]
    FROM
        #Temp

    DROP TABLE #Temp

Expected results


text:
Q: How to access subproject gradle file ext properties from root project gradle file I have a subproject Gradle like
project.ext.foo = "bar"
...

And I have the root project Gradle file as
subprojects {
    if (project.hasProperty("foo")) {
        // not true
    }

    def hasFoo = project.findProperty('foo') ?: ""
    // not finding it

}

I need to configure the subprojects in the root gradle file based on a project set or not set in the individual subproject.
I tried to dump with project.properties.each {} but cannot spot the property I am setting.

A: In multiproject builds, Gradle will first evaluate and configure the root project, and then configure sub-projects.
So in your root project subprojects closure you try to access sub-project properties which has not yet been set, since sub-project has not been configured yet.
Adding some debug logs can help to understand the configuration lifecycle:
root project build.gradle
println("root: start configure phase for root project")

subprojects {
    println("root: configuring subproject $project.name")
    if (project.hasProperty("foo")) {
        println("root: property 'foo' found on subproject $project.name")
    } else {
        println("root: property 'foo' !! NOT !!  found on subproject $project.name")
    }
}

println("root: end configure phase for  root project")

subproject build.gradle
println("sub-1: start configure phase for subproject $project.name")

println("sub-1: setting foo property")
project.ext.foo = "bar"

println("sub-1: end configure phase for subproject $project.name")

Execution result:
> Configure project :
root: start configure phase for root project
root: configuring subproject sub1
root: property 'foo' !! NOT !!  found on subproject sub1
root: end configure phase for  root project

> Configure project :sub1
sub-1: start configure phase for subproject sub1
sub-1: setting foo property
sub-1: end configure phase for subproject sub1

BUILD SUCCESSFUL in 206ms

Solutions
A first simple solution would be to use the project.afterEvaluate { } feature in your root project, to make sure subprojects have been configured before configuring things that depend on the foo property :
root project build.gradle
subprojects {
    afterEvaluate {
        println("root: configuring subproject $project.name")
        if (project.hasProperty("foo")) {
            println("root: property 'foo' found on subproject $project.name")
        } else {
            println("root: property 'foo' !! NOT !!  found on subproject $project.name")
        }
    }
}

Result:
> Configure project :
root: start configure phase for root project
root: end configure phase for  root project

> Configure project :sub1
sub-1: start configure phase for subproject sub1
sub-1: setting foo property
sub-1: end configure phase for subproject sub1
root: configuring subproject sub1
root: property 'foo' found on subproject sub1   <<<=== OK !

A better solution to handle shared configuration between subprojects would be to use plugins: please have a look at this dedicated documentation


text:
Q: Move a character in flash randomly I have a character imported to my stage, but I want a button called "Random" that when hit, moves the character either up down left or right, every time you click it. Here's what I tried, but the character will just move diagonally.
//import the code to use the components
import fl.events.ComponentEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;

//stay on this frame
stop();

//declare variables
var RandomNumber:Number = Math.floor(Math.random() * 5) -5;
var XMove:Number;
var YMove:Number;
var tmrMove:Timer = new Timer(25);

btnRandom.addEventListener(ComponentEvent.BUTTON_DOWN, RandomNum);
//listen for timer to tick
tmrMove.addEventListener(TimerEvent.TIMER, onTick);

function RandomNum(e:ComponentEvent) {
    XMove = RandomNumber;
    YMove = RandomNumber;
    tmrMove.start()
}

//function for timer
function onTick (e:TimerEvent) {
//move the ninja
picNinja.x = picNinja.x + XMove;
picNinja.y = picNinja.y + YMove;

//check if ninja goes off stage
if (picNinja.x > stage.stageWidth) {
    picNinja.x = 0;
}
if (picNinja.x < 0) {
    picNinja.x = stage.stageWidth;
}
if(picNinja.y > stage.stageHeight) {
    picNinja.y = 0;
}
if(picNinja.y < 0) {
    picNinja.y = stage.stageHeight;
}

//function to stop the timer
function stopApp (e:ComponentEvent) {
tmrMove.stop();
}

I thought assigning a random value would work(between 5 and -5) but something is definitely wrong here.

A: In your code, XMove is always equal to YMove, and the value of RandomNumber won't change when you call RandomNum(e:ComponentEvent) function.so the character will just move diagonally.
Try this.
function getRandomNumber():Number{
 //return a random number in range. Math.random() * (max - min + 1)) + min;
    return Math.floor(Math.random() * (5  + 5 + 1)) -5;
}

function RandomNum(e:ComponentEvent) {
    XMove = 0;
    YMove = 0;
    var direction:int = Math.floor(Math.random()*2);//horizontal or Vertical
    //either up down left or right
    switch(direction){
         case 0:
             XMove = getRandomNumber();
             break;
         case 1:
             YMove = getRandomNumber();
             break;
    }

    tmrMove.start()
}


text:
Q: How to embed an angular element inside an angular application? I have an angular element, goes with custom tagname - fancy-button. How can I embed fancy-button in a angular application?
I have tried the following ways, but none of them worked -

*

*Imported angular-element script in index.html/angular.json[scripts] and embedded fancy-button in app.component.html (root component running in angular application)

*Imported angular-element script in app.component.html and also embedded fancy-button in app.component.html (root component running in angular application)
Thanks

A: To index.html, I added:
<script type="text/javascript" src="assets/cappapproot.js"></script>

(cappapproot.js is the name of my Angular Element js)
This caused an Uncaught Error: Zone already loaded. To resolve this error, in pollyfills.ts I commented out the line:
import 'zone.js/dist/zone';  // Included with Angular CLI.

A: in the end, I managed to implement the custom element in my application. You should do the next steps:

*

*In your angular.json add the script file in your selected project:

    ...,
    "projects": {
        "my-awesome-project": {
        ...,
        "architect": {
            "build": {
                "options":{
                    ...,
                    "scripts": [
                        ...,
                        "[path to your awesome Element js]/[awesome-element].js"
                    ],
                    ...
                 },
             ...
         },
         ...
     }

*In your polyfills files include import 'zone.js/dist/zone';  // Included with Angular CLI. at the end of the file.

*In the module you want to include your Angular element you must add the CUSTOM_ELEMENTS_SCHEMA in the schemas parameter of the decorator:
@NgModule({
  declarations: [...],
  imports: [
    CommonModule,
    ...
  ],
  schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})

A: Are you absolutely sure your using the correct element name? Can you post your component + usage?


text:
Q: How do you make a block of code that contains return statements into a function? If I have a similar block of code that is used in many places with different functionality but contains return statements, how can I restructure it to make this block into a function? For example, lets say I have an object Mailman that contains a validity code (success/fail/reason for failure) and also possibly a package to give the callee.
In one case the mailman might just grab his item that's held and give it to the callee:
Mailman mailman = requestMailForPerson(person);

switch(mailman.getStatus()){
   case SUCCESS:
      Mail mail = (Mail)mailman.getHeldItem();
      return Response.ok().entity(mail).build();
   case PERSON_DOESNT_EXIST:
      return Response.status(Response.status.BAD_REQUEST).build();
   case MAIL_SERVICE_FAILED_SOMEWHERE:
      return Response.status(Response.status.INTERNAL_SERVER_ERROR).build();
}

But in another he might be rerouting a letter
Mailman mailman = rerouteLetterForPerson(letter, person);

switch(mailman.getStatus()){
   case SUCCESS:
      Letter letter = (Letter)mailman.getHeldItem();
      if(distance(letter.address, currentLocation) > 50){
          sendToNextoffice(letter);
          return Response.ok.entity("in transit").build();
      }else{
          return Response.ok().entity(letter).build();
      }

   case PERSON_DOESNT_EXIST:
      return Response.status(Response.status.BAD_REQUEST).build();
   case MAIL_SERVICE_FAILED_SOMEWHERE:
      return Response.status(Response.status.INTERNAL_SERVER_ERROR).build();
}

There are just blocks of code that look really similar, and I want to break out this logic somewhere, but handling the different success/fail scenarios is giving me a hard time.

A: You already have "half" of your answer in your code:
Mailman mailman = requestMailForPerson(person);

vs.
Mailman mailman = rerouteLetterForPerson(letter, person);

The key point here is: those should not be the "same" Mailman class objects. Mailman could be an interface and your methods return different implementations of that!
And then you just call a method like
mailman.doYourJob();

and you get the correct result; depending on the underlying implementation code!
You are fully correct in the sense that such switch on internal status code has a very bad smell. It violates the Tell Don't Ask principle. That is the part that you really want to avoid: you do not want to externalize that status, and have other "external" code make decisions based on that!

A: You could just add a flag to your function that states whether or not to check the distance:
bool checkStatus(Mailman& toCheck, bool checkDistance)
{
   switch(toCheck.getStatus()){
   case SUCCESS:
      Letter letter = (Letter)mailman.getHeldItem();
      if(checkDistance && distance(letter.address, currentLocation) > 50){
          sendToNextoffice(letter);
          return Response.ok.entity("in transit").build();
      }else{
          return Response.ok().entity(letter).build();
      }

      case PERSON_DOESNT_EXIST:
          return Response.status(Response.status.BAD_REQUEST).build();
      case MAIL_SERVICE_FAILED_SOMEWHERE:
          return Response.status(Response.status.INTERNAL_SERVER_ERROR).build();
    }

}

Then you have use-case 1:
Mailman mailman = requestMailForPerson(person);
return checkStatus(mailman, false);

And use-case 2:
Mailman mailman = rerouteLetterForPerson(letter, person);
return checkStatus(mailman, true);

A: If you want to reduce code duplication and make the code a bit more readable, a callback function might be a viable option. Just "tell" the method what to do in the SUCCESS case.
public process(Mailman mailman, Function<Mailman, Object> onSuccess) {
    switch (mailman.getStatus()) {
    case SUCCESS:
        return Response.ok().entity(onSuccess.apply(mailman)).build();
    case PERSON_DOESNT_EXIST:
        return Response.status(Response.status.BAD_REQUEST).build();
    case MAIL_SERVICE_FAILED_SOMEWHERE:
        return Response.status(Response.status.INTERNAL_SERVER_ERROR).build();
    }
}

When calling the function, just pass in the callback as an anonymous function or even just a method reference:
process(requestMailForPerson(person), Mailman::getHeldItem);

process(rerouteLetterForPerson(theLetter, person),
        mailman -> {
            Letter letter = (Letter) mailman.getHeldItem();
            if (distance(letter.address, currentLocation) > 50){
                sendToNextoffice(letter);
                return "in transit";
            } else {
                return letter;
            }
        });


text:
Q: Weird Termimal Prompt Mac OSX I did an update to Mojave and now when I go to the terminal is says:
csarson:~ janet$
it never had the csarson:~ part before.  I checked and there is no user with this name.  Is it something I should be concerned with?  Does anyone know if it a bash profile of some kind?
Thanks in advance,
Janet

A: I believe that is the name of your computer. The terminal prompt format is:
Computer-Name:{working-directory} {username}$

So in this case csarson is your computer's name. See the image below for how it looks on my MacBook Pro, also running Mojave.


text:
Q: How to subtract two times in shell I nee to subtract two lines which is in the format of time in shell.
The time format is hh:mm:ss
I used the code below to get the time.
cat /var/log/kern.log |grep usb |tail -2| awk '{print $3}'

The output of the above code is
18:23:24
18:20:20

How can I find the difference in seconds?

A: A more general solution because it works with times from different dates, too:
echo "18:23:24
18:20:20" |
  (read later_time; read former_time;
    former_seconds=$(date --date="$former_time" +%s);
    later_seconds=$(date --date="$later_time" +%s);
    echo $((later_seconds-former_seconds)) )
184

A: I would take a step further (inspired by this post):
# => 18:23:24 --> 66204
grep usb /var/log/kern.log|tail -2|awk '{print $3}'|awk -F: '{print ($1 * 3600) + ($2 * 60) + $3 }'

So, after I had:
66204
66020

You could then do:
echo $((66204-66020)) # => 184

A: If you use awk you can do it in one invocation
awk '
/usb/{
("date +%s -d "$3)|getline t[++i];
}
END{
print t[i-1]-t[i];
}' /var/log/kern.log

A: Your entire pipeline in awk without lots of unnecessary pipes.
Similar to costas but without using any external commands.
awk '/usb/{split($3,a,":");b[++x]=(a[1]*3600)+(a[2]*60)+a[3]}END{print b[x-1]-b[x]}' /var/log/kern.log

Heres just the last bit with the dates worked out if you decide to keep the pipes
 awk '{split($1,a,":");b[x++]=(a[1]*3600)+(a[2]*60)+a[3]}END{print b[0]-b[1]}'


text:
Q: Global hooks in Serenity BDD I was trying to implement global hooks in serenity-bdd project. As I browse through found below links and none of them worked for me. Some of them not specific to Serenity-BDD though.
package mypackage;

import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import net.serenitybdd.cucumber.CucumberWithSerenity;

@RunWith(CucumberWithSerenity.class)
@CucumberOptions(
        features = "src/test/resources/features",
        glue = {"MyProj.cucumber.stepdefinition"},
public class MyTest {

         @Before
         public static void setUp() {
                 //do something here
         }

}

Solution 1
Solution 2
My Maven versions are:

A: I am not sure I caught your purposes and what you want to do before the test execution. Since you use the Serenity framework I suggest you look at StepListener implementation. It uses Java SPI. Probably it will be useful to you in your task.
In a few words:
Serenity has class StepEventBus which has the logic to load service implementation from classpath before the test execution. You need only to implement your custom StepListener and override methods. And after that, you will be able to run your peace of code on different run stages(feature start, test start, step start, etc.)


text:
Q: laravel horizon - debug job is not running/processed I am using Laravel Horizon to handle queued jobs. Below is my code
<?php

namespace App\Jobs;

class ProcessPodcast implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $podcast;

    public function handle(AudioProcessor $processor)
    {
        // Process uploaded podcast...
        Log::channel('slack')->send('Processing ...');
    }
}

In the job handle method, I have logging to slack channel. When this type of queued jobs is executed, I got the slack msg.
Sometimes, I say 1% to 5%, when I dispatched job ProcessPodcast::dispatch(), I didn't get the slack message. And I didn't get the job showed up under Horizon Failed Job page. This behaviors is totally random. It is very hard to reproduce. I am thinking that:
Case #1: Laravel did not create the job, therefore, no job is executed
Case #2: Laravel created the job, but Horizon didn't run the job
In either case, it would be very helpful to check if a job ProcessPodcast is saved to Redis. I don't think this is possible with Redis.
Please provide recommendations on how to debug this issue.


text:
Q: Form validation in AngularJS-1 I am new to Angularjs. I want to create a form and custom directive to validate each field. Is there any way by which I can create custom validation directives to each possible form fields. Separate validation directives to each form field - ( Text, Password, Text area, Checkbox, Radio button, Drop down, Submit button, Reset button ). Any help or reference is appreciated.

A: Try something like this, this is the standard way to do this-
.directive('validate', function () {
        return {
            restrict: 'A',
            require: 'ngModel',
            link: function (scope, elem, attrs, ngModel) {
               ngModel.$validators.validate = function(modelValue) {
                   //Your logic here, return true if success else false
               }
            }
        };
    });


text:
Q: Retrieve all CS:GO items via Steam API or endpoint I was just wondering, is there anyway to retrieve all CS:GO items some way through the Steam Web API, or a JSON endpoint, or some other alternative? I've looked everywhere for a solution, though, I can't seem to find one. If there is no solution, then how do websites such as: http://csgolounge.com/ and http://csgo.steamanalyst.com/ retrieve all their items?

A: I'm using this to retrieve the data from steam market.
http://steamcommunity.com/market/listings/730/AWP%20%7C%20Asiimov%20%28Field-Tested%29/render?start=0&count=1&currency=3&language=english&format=json
Then modifying the link to get the weapon, skin and exterior I want. There is also this link that can be modified.
http://steamcommunity.com/market/priceoverview/?country=DE&currency=3&appid=730&market_hash_name=AK-47%20%7C%20Redline%20%28Field-Tested%29
This I found from this thread.
Get steam item prices

A: Maybe you should try something like this
https://api.steampowered.com/IEconItems_730/GetSchema/v2/?key=<Steam key>&language=ru


text:
Q: Whois CNAME record not forwarding to heroku custom domain I've added a custom subdomain to my herokuapp as
subdomain.domain.com

pointing to
example.herokuapp.com

In my Whois CNAME records, I've added a new record as follows:
Zone id.    XXXXXXX

Record Id   XXXXXXXX

Name    subdomain.domain.com

Class   IN

Type    CNAME

Status  Active

Value   example.herokuapp.com

TTL 28800

Creation Date   2015-08-08 19:14:54.753498

But this is still not resolving and accessing the url gives me
ERR_NAME_NOT_RESOLVED

When I check my CLI with heroku domains, it gives me the list of domains I've added to the app.
How can I fix this?

A: You don't have access to subdomain.domain.com. Yours should be subdomain.herokuapp.com


text:
Q: Force a push with SourceTree I started using SourceTree a few days ago to manage Mercurial repositories with my Mac. Now I ran into the problem when pushing to my remote repository creates a new head on a new branch and I would like to force it.
However, I am not able to find any specific option in SourceTree which allows me to set the force option for a push. Is it just my inability to find it or is there no possibility to set it?
Thanks in advance
Michael

A: In SourceTree version 2.5.5.0 there is an option for that.
Make sure you have enabled in options:

[Menu] Tools -> Options -> [Tab] Git -> [Section] Enable Force Push

After that, you can force push it using push button in toolbar:

And it works!

A: In SourceTree 3 you can allow it in the advanced tab:

A: SourceTree is finally going to add force push:
https://jira.atlassian.com/browse/SRCTREE-1156
Reason:
https://answers.atlassian.com/questions/54469/how-do-i-perform-a-forced-push-push-f-from-sourcetree
Edit:
It is now added in SourceTree, but you need to turn the option on in the settings.

A: SourceTree (as of ver. 1.4.2) issues a hg push --new-branch as needed, so if you create a new branch (as opposed to having two heads on one branch), you just do a regular push (Repository → Push). You can, optionally, specify a branch you want to push if you have outgoing changesets on several branches.
I wasn't able to find a way to do a hg push --force proper via the SourceTree dialogs. I agree with @Ry4an that this option is more dangerous than useful. I've never done a force push since --new-branch was introduced, and never needed it to combine unrelated repositories or push a two-headed branch (a force pull is much safer).
I conclude that on a rare occasion when a force push is needed, opening Terminal won't hurt. If you disagree, please share your workflow in comments.

A: You can show it on Preferences -> Advanced -> Allow force push

Then force push option would be available.

A: it's now under Sourcetree -> Preferences -> Advanced -> Allow force push


text:
Q: Why does this not work ? $array = explode('?', $str); I have a Chinese paragraph with periods (otherwise known as "full stops") and question marks. I want to explode the paragraph into and array of sentences. I can't seem to get preg_split(/。|?|!/, $str) to work with anything that includes the question mark or exclamation. It ignores the question mark and the exclamation point.
I have tried the following and it works fine:
$array = explode('。', $okresult);

But the following just returns an array with one index filled with the entire paragraph:
$array = explode('?', $okresult);

Here is the paragraph I am trying to split. It isn't grammatically correct, I am just using it as a test:

公元前5世纪,尼希米担任犹太人的省长,他尽心竭力做上帝喜悦的事!例如,他不怕敌人反对,带头重建耶路撒冷的城墙。他执行上帝的律法,关怀受压迫的人,也致力巩固同胞对上帝的信心。上帝有没有留意他这个忠仆的善行呢?尼希米得到耶和华的悦纳吗?我们看看尼希米记的最后一节经文,就知道答案了。

This doesn't work either: mb_split('?', $okresult);

A: You are missing the /u Unicode modifier for preg_split. Also it's shorter to use a character class here:
preg_split('/[。?!]/u', $str)


text:
Q: Parquet Data Ingestion in Druid Error in Timestamp parsing using Joda Context:
I am able to submit a MapReduce job from druid overlord to an EMR. My Data source is in S3 in Parquet format. The timestamp field value is in format "2017-09-01 21:14:11:552 IST".
Error is while parsing the timestamp
Issue Stack trace is:
2018-01-18T19:31:52,509 INFO [task-runner-0-priority-0] org.apache.hadoop.mapreduce.Job - Task Id : attempt_1516108443547_0022_m_000068_0, Status : FAILED
Error: io.druid.java.util.common.RE: Failure on row[{"t": "2017-09-01 21:14:11:552 IST"}]
    at io.druid.indexer.HadoopDruidIndexerMapper.map(HadoopDruidIndexerMapper.java:91)
    at io.druid.indexer.DetermineHashedPartitionsJob$DetermineCardinalityMapper.run(DetermineHashedPartitionsJob.java:288)
    ..

Caused by: java.lang.IllegalArgumentException: Invalid format: "2017-09-01 21:14:11:552 IST" is malformed at "IST"
    at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:945)
    at io.druid.java.util.common.parsers.TimestampParser.lambda$createTimestampParser$4(TimestampParser.java:93)
    at io.druid.java.util.common.parsers.TimestampParser.lambda$createObjectTimestampParser$8(TimestampParser.java:129)
    . .

I have used different set of format that can parse but unable to get a format in joda lib. But, the timestamp format is readable in java.text.SimpleDateFormat see following code:
Sample Java program to parse Date
String text = "2017-09-01 21:14:11:552 IST";
SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS zzz");
TimeZone gmt = TimeZone.getTimeZone("GMT");
sdf.setTimeZone(gmt);
sdf.setLenient(false);

try {
    Date date = sdf.parse(text);
    System.out.println(date);
    System.out.println(sdf.format(date));
} catch (Exception e) {
    e.printStackTrace();
}

Output
Fri Sep 01 21:14:11 IST 2017
2017-09-01 21:14:11:552 IST

Environment:
Druid version: 0.11
EMR version : emr-5.11.0
Hadoop version: Amazon 2.7.3

Druid input json
{
  "type": "index_hadoop",
  "spec": {
    "ioConfig": {
      "type": "hadoop",
      "inputSpec": {
        "type": "static",
        "inputFormat": "io.druid.data.input.parquet.DruidParquetInputFormat",
        "paths": "s3://s3_path"
      }
    },
    "dataSchema": {
      "dataSource": "parquet_test1",
      "granularitySpec": {
        "type": "uniform",
        "segmentGranularity": "DAY",
        "queryGranularity": "ALL",
        "intervals": ["2017-08-01T00:00:00:000Z/2017-08-02T00:00:00:000Z"]
      },
      "parser": {
        "type": "parquet",
        "parseSpec": {
          "format": "timeAndDims",
          "timestampSpec": {
            "column": "t",
            "format": "yyyy-MM-dd HH:mm:ss:SSS zzz"
          },
          "dimensionsSpec": {
            "dimensions": [
              "dim1","dim2","dim3"
            ],
            "dimensionExclusions": [],
            "spatialDimensions": []
          }
        }
      },
      "metricsSpec": [{
        "type": "count",
        "name": "count"
      },{
          "type" : "count",
          "name" : "pid",
          "fieldName" : "pid"
        }]
    },
    "tuningConfig": {
      "type": "hadoop",
      "partitionsSpec": {
        "targetPartitionSize": 5000000
      },
      "jobProperties" : {
        "mapreduce.job.user.classpath.first": "true",
        "fs.s3.awsAccessKeyId" : "KEYID",
        "fs.s3.awsSecretAccessKey" : "AccessKey",
        "fs.s3.impl" : "org.apache.hadoop.fs.s3native.NativeS3FileSystem",
        "fs.s3n.awsAccessKeyId" : "KEYID",
        "fs.s3n.awsSecretAccessKey" : "AccessKey",
        "fs.s3n.impl" : "org.apache.hadoop.fs.s3native.NativeS3FileSystem",
        "io.compression.codecs" : "org.apache.hadoop.io.compress.GzipCodec,org.apache.hadoop.io.compress.DefaultCodec,org.apache.hadoop.io.compress.BZip2Codec,org.apache.hadoop.io.compress.SnappyCodec"
      },
      "leaveIntermediate": true
    }
  }, "hadoopDependencyCoordinates": ["org.apache.hadoop:hadoop-client:2.7.3", "org.apache.hadoop:hadoop-aws:2.7.3", "com.hadoop.gplcompression:hadoop-lzo:0.4.20"]
}

Possible solution
 1. How to parse "2017-09-01 21:14:11:552 IST" in joda format

 2. Any config to use SimpleDateFormat for parsing date in timestampSpec, as joda library is used default.

A: You have failed to parse the timezone abbreviation "IST". Such abbreviations are often ambivalent.
In this case, "IST" can stand for: "Europe/Dublin" (Irish Summer Time), "Asia/Jerusalem" (Israel Standard Time), "Asia/Kolkata" (India Standard Time). Looking at your name, I strongly assume that you want India Time.
Now I discuss several possible solutions and their advantages and drawbacks. A time library can use different strategies to resolve zone name ambiguities. Either it allows users to specify explicitly what zone they want (user-preference), or the region/country-information inside the current/associated locale might be used for resolving.
Joda-Time
The ONLY! solution is realized by following code:
String s = "2017-09-01 21:14:11:552 IST";

Map<String, DateTimeZone> preferredJodaZones =
    Collections.singletonMap("IST", DateTimeZone.forID("Asia/Kolkata"));
DateTimeUtils.setDefaultTimeZoneNames(preferredJodaZones); // attention: static (global)
org.joda.time.format.DateTimeFormatter formatter =
    DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss:SSS zzz");
DateTime joda = formatter.parseDateTime(s);
System.out.println(joda);
// 2017-09-01T21:14:11.552+05:30

While this approach based on explicit user-preference will probably satisfy your requirements because you don't need to change your dependency and preferred library, I consider this way as not so great for two reasons:

*

*It uses a static method to set the user preference (potentially vulnerable in multi-thread-environment).

*It requires explicit knowledge which zone abbreviations have to be resolved.

I recommend to set the user preference only once during program initialization. And then you can probably work with Joda.

Old SimpleDateFormat-class
Yes, that works for you but not for me because the locale on my machine is not India. And I get the timestamp/instant of Israel (3.5 hours difference to India). We see that this old class uses the region info of associated locale in the background in order to resolve the name ambiguity, not the explicitly set tz-offset GMT (via sdf.setTimeZone(gmt);).
System.out.println(sdf.format(date)); // 2017-09-01 22:14:11:552 IDT

So please be very cautious where your code is running.

java.time (Java-8 or later)
DateTimeFormatter threeten =
    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS zzz", new Locale("en", "IN"));
ZonedDateTime jdt = ZonedDateTime.parse(s, threeten);
System.out.println(jdt);
// 2017-09-01T21:14:11.552+03:00[Asia/Jerusalem]
// (on my machine! - might work on your machine but is unreliable)

This experiment reveals that the locale information for resolving the tz-ambiguity is unfortunately not used. But it is possible to specify the user-preference via a builder-based approach:
Set<ZoneId> preferredZones = Collections.singleton(ZoneId.of("Asia/Kolkata"));
DateTimeFormatter threeten2 =
    new DateTimeFormatterBuilder()
    .appendPattern("yyyy-MM-dd HH:mm:ss:SSS ")
    .appendZoneText(TextStyle.SHORT, preferredZones)
    .toFormatter();
ZonedDateTime jdt2 = ZonedDateTime.parse(s, threeten2);
System.out.println(jdt2);
// 2017-09-01T21:14:11.552+05:30[Asia/Kolkata]

Here, the user-preference can be given as local parameter to the parser and does not suffer from any multi-thread-problem (better than Joda).

Time4J (my lib)
It can use a builder approach similar to Java-8 to set the user-preference (not shown here), or it can deploy a non-fixed-offset parameter in constructing the formatter or use the locale information parameter (for greatest flexibility).
ChronoFormatter<Moment> time4j =
    ChronoFormatter.ofMomentPattern(
        "yyyy-MM-dd HH:mm:ss:SSS zzz",
        PatternType.CLDR,
        new Locale("en", "IN"), // // uses India for resolving tz-ambiguity
        ZonalOffset.UTC
        // using ASIA.KOLKATA would have higher ranking than locale information
    );
ZonalDateTime zdt = ZonalDateTime.parse(s, time4j);
// convertible to java.time.ZonedDateTime (zdt.toTemporalAccessor())
System.out.println(zdt);
// 2017-09-01T21:14:11,552+05:30[Asia/Kolkata]


text:
Q: How many unique combination of $n$ numbers are there when multiplying $x$ numbers? If you have $n$ numbers and you multiply them in every combination
$$A\cdot A,\  A\cdot B,\ B\cdot A,\ B\cdot B$$
and so on, how many times do you get the same answer? Or, how many times do you get a unique answer? That is just for a product of two numbers, what if you did product of $3, 4,... n$ numbers. Is there a formula that could calculate this?
An example would be, let's say you have numbers $2,3,5,7$. You can do
$$2\cdot 2,\; 2\cdot 3,\; 3\cdot 2, \;3\cdot 3, \;2\cdot 5, \;5\cdot 2, \;3\cdot 5, \; 5\cdot 3,\; 5\cdot 5,\; 2\cdot 7,\; 7\cdot 2, \;3\cdot 7, \;7\cdot 3, \;5\cdot 7,\; 7\cdot 5, \;7\cdot 7$$
With that you get 16 combinations and only 10 unique answers.

A: We assume that we are given a set $S=\{s_1,s_2,\dots,s_n\}$ of $n$ distinct numbers, and want to count the number of numerically distinct products  $a_1a_2\cdots a_k$, where the $a_i$ range over $S$.
The answer very much depends on numerical properties of the numbers in the set $S$. We will find the maximum possible number of numerically distinct products. We get this maximum if, for example, the elements of $S$ are distinct primes, and in many other cases.
Let $P$ be a product of $k$ elements of $S$. Let $x_1$ be the number of copies of $s_1$ that we used to form $P$. Let $x_2$  be the number of copies of $s_2$ that we used, and so on.
Then the $x_i$ are non-negative integers, and $x_1+\cdots+x_n=k$. Furthermore, under our assumptions any solution of $x_1+\cdots +x_n=k$ in non-negative integers gives a numerically distinct product.
Thus by Stars and Bars (please see Wikipedia) the number of numerically distinct products, under our assumptions, is $\binom{n+k-1}{n-1}$ or equivalently $\binom{n+k-1}{k}$.
Remark: The case $n=4$, $k=2$ of the OP does not require the above machinery, and neither does $n$ arbitrary, $k=2$. But note that for the case $k=2$, the general formula above gives the answer $\binom{n+1}{2}$.


text:
Q: storing string: final class vs. file from external storage I'm building a Java program. I have a list of person names which is used to check whether a word is a name or not. I don't know if I should store these names in an external file or put them as public static fields in a final class?
Now my list has only 1000 names but what if it's up to 100.000 items?
Thanks for your helps!
Edit - I don't really want to use something like a database as it requires other installations when executing in other machines. A simple txt file sounds good but in order to check the word names, I still have to load all list items (say 10,000 names) into my program and search for names, which makes me a little confused: if it's better than the aforementioned way of pre-defined an array of constants in a final class. Can you help me figure out one effective way to implement this?

A: There's no programming benefit is having the strings in code, so externalize the data to a database.
However, even a flat file is a "database" or sorts, so I would put the task of loading the names behind an interface and leave the implementation to decide how the data is to be loaded:
Some implementation options are:

*

*return hard coded values

*read values from a file

*read from an SQL database

*read from a NoSQL database

*read from a web service

Pick the implementation that works best for you now - it's easy to change if you need later on.
An example interface:
public interface NameLoader {
    public List<String> getNames();
}

Have your main program use one of these and supply the implementation using a factory method:
public class NameLoader() {
    public NameLoader createNameLoader() {
        // code the implementation you're currently using here
        return new FileBasedNameLoader();
    }
}

You could go further and externalise the class to use via Spring or properties file etc.

A: Anything over 100 or more strings i would suggest some form of database or other means of storing the data.. If the array of names that is currently 1000 could grow or shrink in size.. Then you would best want a database so you do not have to modify the program each time an entry/query/edit has been done.
If you are trying to keep the application itself VERY basic and do not wish to result to something like a SQL or other DB.. You might want to look at Flat File db's or along those lines.
EDIT -
Even something as simple as a *.txt file that has a comma separated array with all the names in it can be simple and effective if done right.

A: Use an external persistence mechanism of some kind; e.g. a file, a database, etcetera.  There are many ways to do this, and which is best depends on your (complete) application's requirements.

Now my list has only 1000 names but what if it's up to 100,000 items?

Well, right now, it will work (sort of).  But when you scale up, you will start to run into hard limits imposed by the JVM specification.  For instance:

*

*There is a hard limit on the number of constants (e.g. String literals) in the constant pool.

*There is a hard limit on the size of a single method or constructor.  (That includes the synthetic method that does a classes static initialization.)

Another problem with the "hard-wired list in the code" approach that you would need to edit the source code and recompile it each time you changed the list.  That is not practical for a production-quality system.

A simple txt file sounds good ....

It is, if you don't need the power of a database; see below.

... but in order to check the word names, I still have to load all list items (say 10,000 names) into my program ...

That is correct.  But it is hardly a problem!  You should be able to implement the file loading in 10 or so lines of code.  And it shouldn't be appreciably slower than embedding the data in your class file.  (After all, the class loader has to read the entire classfile and turn all of the embedded data into intern'd String objects.)

... and search for names

But that's no different from if you had the list of names hard-wired.  You have to search the list whether it is loaded from a file into an array / list , or if the array / list is created and initialized from a bunch of string literals in your code.

which makes me a little confused: if it's better than the aforementioned way of pre-defined an array of constants in a final class

It is.  For the reasons that were listed above, and in other answers.

For the record:

*

*if you need to repeatedly search your long list of names, then it is better (more efficient) to load them into a HashSet.  That gives faster search times.

*if you only need to do the search a small number of times and/or if the list is really large, then a database is more efficient.  It will have fast search times, AND it will avoid the need to read the entire dataset into memory.


text:
Q: Acer Aspire One, system slow. Graphics problem? I have a Acer Aspire One
Intel Atom CPU N280 1.66GHz
2gb RAM
Video:
Intel Mobile 945GSE Express Integrated Graphics Controller
It was running Windows Vista before, and was very slow. I tried to change to Ubuntu, but is even slower.
This computer is even certified in Ubuntu website:
http://www.ubuntu.com/certification/hardware/200908-3469/
I installed the 32-bits as recomended for 2gb RAM.
The system works well, showing only problems in graphic parts, such as minimizing windows and opening the search window.
EDIT:
I have searched the forum and I have seen many similar problems. and believe that problems are the graphic drivers and / or graphic efects. None of the other questions helped
The System Monitor is is showing the CPU usage at 100% constantly

A: I don't think Ubuntu would have issues with the Intel graphics but you could try the following:

*

*Change the desktop environment

*Disable startups

and more information can be found here :
http://ubuntuforums.org/showthread.php?t=1997932
which also points to:
http://www.howtogeek.com/115797/6-ways-to-speed-up-ubuntu/

A: First of all a couple words about distribution you download. According to the documentation for your CPU it's 32 Bit , that's why you download Ubuntu 32 bit. Most 32-bit OSes really only let individual applications use 2 GB of RAM, even if you have 4 GB installed. On the other hand if you would have 64bit CPU event with 2Gb of RAM you could install 64 bit OS for performance benefits.
However the machine you have is really slow, I tried myself Ubuntu on it and the slow things made me crazy. I tried it with SSD insead of HDD and that was a bit of change, I stopped waiting for ages. So it's where we are, you can also get performance increase on it with SSD.

A: This computer is certified for Ubuntu 12.04 LTS. This does not mean that 14.04 will not work, however for better performance (more specifically Ubuntu Certified performance) it most likely will be best if you use 12.04.
12.04's release cycle and EOL can be seen here. So you still have time to use Ubuntu, before you get a new laptop, or switch to a different OS.


text:
Q: How do websites encrypt API response? When we see API response of some big websites in google chrome network tab we see an encrypted response from the server. The response is nothing but a hex code. My question is how do they encrypt and decrypt the response?
This is a part of a response from an API
[encoded data, 5025 characters]

A: That's not encrypted nor is it hex. That's just Base64 encoded. It's a RIFF image:
$ echo "..." | base64 -D > x
$ file x
RIFF (little-endian) data, Web/P image, VP8 encoding, 140x312, Scaling: [none]x[none], YUV color, decoders should clamp

Seems like it's transparent, though. Use Chrome to open it.


text:
Q: Recipient.AutoResponse property returns empty string Using Outlook 2016, I'm trying to retrieve the AutoResponse (https://learn.microsoft.com/en-us/office/vba/api/outlook.recipient.autoresponse) property for a recipient who is sending an out of the office message.
I get an empty string.
I check that the recipient is resolved through the .Resolved property and I see the auto message displayed if I pass the objMail.Display command. Am I missing something or is this a bug in Outlook?
Sub test()
Dim objMail As Outlook.MailItem
Dim objRecipient As Outlook.Recipient
Set objMail = Application.CreateItem(olMailItem)
Set objRecipient = objMail.Recipients.Add("alias@domain.com")
objRecipient.Resolve
MsgBox objRecipient.AutoResponse
End Sub

The related thread, as well as the answer it references, suggest alternatives (EWS and Redemption) that are not feasible due to access restrictions, and don't explore the potential root cause for .AutoResponse not behaving as described in the documentation.

A: The Recipient.AutoResponse property returns or sets a string representing the text of automatic response for a Recipient. So, you may try to set the property to any string and then check it later.
The Display method of the MailItem class displays a new Inspector object for the item. It doesn't show up an auto-response string.

A: Recipient.AutoResponse property is local to the message - it returns PR_RECIPIENT_AUTORESPONSE_PROP (0x5FFA001F) property from the message recipient table. It does not returns the OOF status.


text:
Q: How to route, group, or otherwise split up messages into consistent sets using TPL Dataflow I'm new to TPL Dataflow and I'm looking for a construct which will allow splitting up a list of source messages for evenly distributed parallel processing while maintaining order of the messages message through individual pipelines. Is there a specific Block or concept within the DataFlow API that can be used to accomplish this or is it more of a matter providing glue code or custom Blocks between existing Blocks?
For those familiar with Akka.NET I'm looking for functionality similar to the ConsistentHashing router which allow sending messages to a single router which then forwards these messages on to individual routees to be handled.
Synchronous example:
var count = 100000;
var processingGroups = 5;
var source = Enumerable.Range(1, count);

// Distribute source elements consistently and evenly into a specified set of groups (ex. 5) so that.
var distributed = source.GroupBy(s => s % processingGroups);

// Within each of the 5 processing groups go through each item and add 1 to it
var transformed = distributed.Select(d => d.Select(i => i + 3).ToArray());

List<int[]> result = transformed.ToList();
Check.That(result.Count).IsEqualTo(processingGroups);
for (int i = 0; i < result.Count; i++)
{
    var outputGroup = result[i];

    var expectedRange = Enumerable.Range(i + 1, count/processingGroups).Select((e, index) => e + (index * (processingGroups - 1)) + 3);
    Check.That(outputGroup).ContainsExactly(expectedRange);
}

A: In general I don't think what you're looking for is pre-made in Dataflow as it may be with a ConsistentHashing router. However, by adding an id to the pieces of data you wish to flow you can process them in any order, in parallel and reorder them when the processing finishes.
public class Message {
        public int MessageId { get; set; }
        public int GroupId { get; set; }
        public int Value { get; set; }
    }

    public class MessageProcessing
    {
        public void abc() {
            var count = 10000;
            var groups = 5;
            var source = Enumerable.Range(0, count);

            //buffer all input
            var buffer = new BufferBlock<IEnumerable<int>>();

            //split each input enumerable into processing groups
            var messsageProducer = new TransformManyBlock<IEnumerable<int>, Message>(ints =>
            ints.Select((i, index) => new Message() { MessageId = index, GroupId = index % groups, Value = i }).ToList());

            //process each message, one action block may process any group id in any order
            var processMessage = new TransformBlock<Message, Message>(msg =>
            {
                msg.Value++;
                return msg;
            }, new ExecutionDataflowBlockOptions() {
                MaxDegreeOfParallelism = groups
            });

            //output of processed message values
            int[] output = new int[count];

            //insert messages into array in the order the started in
            var regroup = new ActionBlock<Message>(msg => output[msg.MessageId] = msg.Value,
                new ExecutionDataflowBlockOptions() {
                    MaxDegreeOfParallelism = 1
                });
        }

    }

In the example the GroupId of a message isn't used but it could be used in a more complete example for coordinating groups of messages. Also, handling follow up posts to the bufferblock could be done by changing the output array to a List and setting up a corresponding list element each time an enumerable of integers is posted to the buffer block. Depending on your exact use, you may need to support multiple users of the output, and this can be folded back into the flow.

A: You can dynamically create a pipeline with linking the blocks between each other based on predicate:
var count = 100;
var processingGroups = 5;
var source = Enumerable.Range(1, count);

var buffer = new BufferBlock<int>();
var consumer1 = new ActionBlock<int>(i => {  });
var consumer2 = new ActionBlock<int>(i => {  });
var consumer3 = new ActionBlock<int>(i => {  });
var consumer4 = new ActionBlock<int>(i => { Console.WriteLine(i); });
var consumer5 = new ActionBlock<int>(i => {  });

buffer.LinkTo(consumer1, i => i % 5 == 1);
buffer.LinkTo(consumer2, i => i % 5 == 2);
buffer.LinkTo(consumer3, i => i % 5 == 3);
buffer.LinkTo(consumer4, i => i % 5 == 4);
buffer.LinkTo(consumer5);

foreach (var i in source)
{
    buffer.Post(i);
    // consider async option if you able to do it
    // await buffer.SendAsync(i);
}
buffer.Complete();
Console.ReadLine();

The code above will write only numbers from 4th group, processing other groups silently, but I hope you got the idea. There is a general practice to link a block for at least one consumer without filtering for messages not being dropped if they aren't accepted by any consumers, and you can do this if you don't have a default handler (NullTarget<int> simply ignores all the messages it got):
buffer.LinkTo(DataflowBlock.NullTarget<int>());

The downside of this is a continuation of it's advantages: you have to provide predicates, as there is no built-in structures for this. However, it still could be done.


text:
Q: AltBeacon setBeaconLayout() I would like to know what the Beacon Code stands for.
I mean, as far as I know it should identify the beacon layout.
Does this mean that I can customize any sort of layout and assign to it any sort of Beacon Code?
I mean, can I write something like that:
setBeaconLayout("m:2-3=abcd,i:4-13,i:14-23,p:24-24,d:25-25")?
Thanks for your help

A: According to AltBeacon docs:

m - matching byte sequence for this beacon type to parse (exactly one
required)
s - ServiceUuid for this beacon type to parse (optional, only for
Gatt-based beacons)
i - identifier (at least one required, multiple allowed)
p - power calibration field (exactly one required)
d - data field (optional, multiple allowed)
x - extra layout.  Signifies that the layout is secondary to a primary
layout with the same matching byte sequence (or ServiceUuid).  Extra
layouts do not require power or identifier fields and create Beacon
objects without identifiers.
Example of a parser string for AltBeacon:
"m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"
This signifies that the beacon type will be decoded when an
advertisement is found with 0xbeac in bytes 2-3, and a three-part
identifier will be pulled out of bytes 4-19, bytes 20-21 and bytes
22-23, respectively. A signed power calibration value will be pulled
out of byte 24, and a data field will be pulled out of byte 25.

here is a list of some beacon layouts
ALTBEACON      m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25
EDDYSTONE TLM  x,s:0-1=feaa,m:2-2=20,d:3-3,d:4-5,d:6-7,d:8-11,d:12-15
EDDYSTONE UID  s:0-1=feaa,m:2-2=00,p:3-3:-41,i:4-13,i:14-19
EDDYSTONE URL  s:0-1=feaa,m:2-2=10,p:3-3:-41,i:4-20v
IBEACON        m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24


text:
Q: What is "editor-render-0" in flotr I am seeing a flotr example where (document.getElementById("editor-render-0") is used at the end phase of the coding. I am not getting why "editor-render-0" is used ans what is it. Please explain this it will helps me to understand the whole coding of the flotr.
This is a function where "editor-render-0" is used-
(function basic(container) {

  var
    d1 = [[0, 3], [4, 8], [8, 5], [9, 13]], // First data series
    d2 = [],                                // Second data series
    i, graph;

  // Generate first data set
  for (i = 0; i < 14; i += 0.5) {
    d2.push([i, Math.sin(i)]);
  }

  // Draw Graph
  graph = Flotr.draw(container, [ d1, d2 ], {
    xaxis: {
      minorTickFreq: 4
    },
    grid: {
      minorVerticalLines: true
    }
  });
})(document.getElementById("editor-render-0"));

A: This isn't really anything specific to flotr. This is what's called an "Immediately Executing Function" or "Immediately Invoked Function Expression" (IIFE).
There are several reasons to use IIFEs:
The first is that any variables defined inside the function (in this case "d1", "d2", "i", and "graph"). This keeps those variables from polluting the global scope.
The second reason/benefit is encapsulation of external variables. When the function is invoked, you're passing in the result of document.getElementById("editor-render-0") (presumably a div with id "editor-render-0").
Instead, they could have written this:
var
  container = document.getElementById("editor-render-0");
  d1 = [[0, 3], [4, 8], [8, 5], [9, 13]], // First data series
  d2 = [],                                // Second data series
  i, graph;

// Generate first data set
for (i = 0; i < 14; i += 0.5) {
  d2.push([i, Math.sin(i)]);
}

// Draw Graph
graph = Flotr.draw(container, [ d1, d2 ], {
  xaxis: {
    minorTickFreq: 4
  },
  grid: {
    minorVerticalLines: true
  }
});

This is almost equivalent to the original example, except that in this code sample the "container", "d1", "d2", "i", and "graph" variables would be defined on the global scope.
This is a code snippet that would be exactly equivalent in behavior.
(function() {
  var
    container = document.getElementById("editor-render-0");
    d1 = [[0, 3], [4, 8], [8, 5], [9, 13]], // First data series
    d2 = [],                                // Second data series
    i, graph;

  // Generate first data set
  for (i = 0; i < 14; i += 0.5) {
    d2.push([i, Math.sin(i)]);
  }

  // Draw Graph
  graph = Flotr.draw(container, [ d1, d2 ], {
    xaxis: {
      minorTickFreq: 4
    },
    grid: {
      minorVerticalLines: true
    }
  });
})();


text:
Q: How to use the same R recode function on multiple variables without coding each? From the recode examples, what if I have two variables where I want to apply the same recode?
factor_vec1 <- factor(c("a", "b", "c"))
factor_vec2 <- factor(c("a", "d", "f"))

How can I recode the same answer without writing a recode for each factor_vec? These don't work, do I need to learn how to use purrr to do it, or is there another way?
Output 1: recode(c(factor_vec1, factor_vec2), a = "Apple")
Output 2: recode(c(factor_vec2, factor_vec2), a = "Apple", b =
"Banana")

A: If there are not many items needed to be recoded, you can try a simple lookup table approach using base R.
v1 <- c("a", "b", "c")
v2 <- c("a", "d", "f")

# lookup table
lut <- c("a" ="Apple",
         "b" = "Banana",
         "c" = "c",
         "d" = "d",
         "f" = "f")

lut[v1]
lut[v2]

You can reuse the lookup table for any relevant variables. The results are:
> lut[v1]
       a        b        c
 "Apple" "Banana"      "c"

> lut[v2]
      a       d       f
"Apple"     "d"     "f"

A: Use lists to hold multiple vectors and then you can apply same function using lapply/map.
library(dplyr)
list_fac <- lst(factor_vec1, factor_vec2)
list_fac <- purrr::map(list_fac, recode, a = "Apple", b = "Banana")

You can keep the vectors in list itself (which is better) or get the changed vectors in global environment using list2env.
list2env(list_fac, .GlobalEnv)


text:
Q: Is Inverse Search possible after the PDF file has been modified (e.g. annotated) (with Auctex and Okular) I have configured Okular and Auctex so that forward and inverse search work like a charm when I have the *.tex file open and after I compiled the PDF file. I do, however, often encounter a scenario where some other person comments, corrects or annotates this PDF file. Is there a way to configure okular (or any other PDF viewer) and emscas in a way that inverse seach is still working under these conditions? I.e. under conditions where I cannot recompile the PDF file?

A: The answer is yes.
The .synctex.gz file links your TeX source file and the PDF output by postion. Supposing you complied test.tex and got the test.pdf file, you can find that even if you replace test.pdf by aaaa.pdf, forward and inverse searching will still work---position is right, however, the contents can be quite different.