text:
Q: How I can run my TimerTask everyday 2 PM? I want to execute a job everyday 2PM. Which method of java.util.Timer I can use to schedule my job?
After 2Hrs, run it will stop the job and reschedule for next day 2PM.

A: Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 2);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);

// every night at 2am you run your task
Timer timer = new Timer();
timer.schedule(new YourTask(), today.getTime(), TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS)); // period: 1 day

A: The easiest way I've found of doing this has always been through Task Scheduler in Windows and cron in Linux.
However for Java, take a look at Quartz Scheduler
From their website:

Quartz is a full-featured, open source job scheduling service that can
  be integrated with, or used along side virtually any Java EE or Java
  SE application - from the smallest stand-alone application to the
  largest e-commerce system. Quartz can be used to create simple or
  complex schedules for executing tens, hundreds, or even
  tens-of-thousands of jobs; jobs whose tasks are defined as standard
  Java components that may execute virtually anything you may program
  them to do. The Quartz Scheduler includes many enterprise-class
  features, such as JTA transactions and clustering.

A: Most answers for this question and the following two questions assume that the milliseconds per day is always the same.
How to schedule a periodic task in Java?
How to run certain task every day at a particular time using ScheduledExecutorService?
However, it's not ture due to day lights saving and leap seconds.
This means that if your service is alive for years and the accuracy of the timer matters,
a fixed period timer is not your choice.
So, I'd like to introduce my code snippet for a more flexible timer than the java.util.Timer.
package szx;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.function.Function;

public class ScheduledExecutor {
  public void scheduleRegularly(Runnable task, LocalDateTime firstTime,
                                Function<LocalDateTime, LocalDateTime> nextTime) {
    pendingTask = task;
    scheduleRegularly(firstTime, nextTime);
  }

  protected void scheduleRegularly(LocalDateTime firstTime,
                                   Function<LocalDateTime, LocalDateTime> nextTime) {
    new Timer().schedule(new TimerTask() {
      @Override
      public void run() {
        scheduleRegularly(nextTime.apply(firstTime), nextTime);
        pendingTask.run();
      }
    }, Date.from(firstTime.atZone(ZoneId.systemDefault()).toInstant()));
  }

  private volatile Runnable pendingTask = null;
}

Then, you can execute your job everyday 2PM by invoking the above method in the following way.
new ScheduledExecutor().scheduleRegularly(() -> {

    // do your task...

}, LocalDateTime.now().truncatedTo(ChronoUnit.DAYS).withHour(14), thisTime -> thisTime.plusDays(1));

The basic idea behind the code is to recalculate the left time to the next tick and start a new timer every time.

A: You should try using scheduleAtFixedRate (this will repeat your task). You will need to create an TimerTask object which will specify what to run (in run()) and when to run (scheduledExecutionTime). scheduleAtFixedRate also allows you to specify the first date of execution.

A: Why don't you use Spring's @Scheduled(cron="0 0 14 * * *") .. for sec, min, hours, day, month, dayOfWeek. V Cool. You can even specify 9-11 for 9:00 to 11:00, or MON-FRI in last parameter.
You can invoke this programatically too, like is case of most of Spring, in case you want to set the time at runtime.
See this:-
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html
Adding an example
   @Scheduled(cron="0 0 14 * * *")
    public void customScheduler(){
        try{
            // do what ever you want to run repeatedly
        }catch(Exception e){
            e.printStackTrace();

        }
    }

also please annotate the class containing this with @Component annotation and please provide @EnableScheduling in the Application.java (class contains the main method) class to make spring aware that you are using taskscheduler in your applicaiton.

A: You could use Timer.schedule(TimerTask task, Date firstTime, long period) method, setting firstTime to 2PM today and the setting the period to 24-hours:

Schedules the specified task for repeated fixed-delay execution, beginning at the specified time. Subsequent executions take place at approximately regular intervals, separated by the specified period.

A: import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Timer;
import java.util.TimerTask;

public class MyTimerTask extends TimerTask {
    private final static long ONCE_PER_DAY = 1000*60*60*24;

    //private final static int ONE_DAY = 1;
    private final static int TWO_AM = 2;
    private final static int ZERO_MINUTES = 0;

    @Override
    public void run() {
        long currennTime = System.currentTimeMillis();
        long stopTime = currennTime + 2000;//provide the 2hrs time it should execute 1000*60*60*2
          while(stopTime != System.currentTimeMillis()){
              // Do your Job Here
            System.out.println("Start Job"+stopTime);
            System.out.println("End Job"+System.currentTimeMillis());
          }
    }
    private static Date getTomorrowMorning2AM(){

        Date date2am = new java.util.Date();
           date2am.setHours(TWO_AM);
           date2am.setMinutes(ZERO_MINUTES);

           return date2am;
      }
    //call this method from your servlet init method
    public static void startTask(){
        MyTimerTask task = new MyTimerTask();
        Timer timer = new Timer();
        timer.schedule(task,getTomorrowMorning2AM(),1000*10);// for your case u need to give 1000*60*60*24
    }
    public static void main(String args[]){
        startTask();

    }

}

A: use public void schedule(TimerTask task,Date firstTime,long period)
to make the task repeats again the next day, just set period to 86400000 milliseconds ( which means 1 day )
Date date2pm = new java.util.Date();
date2pm.setHour(14);
date2pm.setMinutes(0);

Timer timer = new Timer();

timer.sc(myOwnTimerTask,date2pm, 86400000);

A: Due java.util.Timer:

Java 5.0 introduced the java.util.concurrent package and one of the
  concurrency utilities therein is the ScheduledThreadPoolExecutor which
  is a thread pool for repeatedly executing tasks at a given rate or
  delay. It is effectively a more versatile replacement for the
  Timer/TimerTask combination, as it allows multiple service threads,
  accepts various time units, and doesn't require subclassing TimerTask
  (just implement Runnable). Configuring ScheduledThreadPoolExecutor
  with one thread makes it equivalent to Timer.

so (add this code to your class):
private ScheduledExecutorService scheduledExecutorService;

    public ScheduledSendLog() {
        init();
    }

    public void destroy() {
        this.scheduledExecutorService.shutdown();
    }

    private void init() {
        scheduledExecutorService =
                Executors.newScheduledThreadPool(1);
        System.out.println("---ScheduledSendLog created " + LocalDateTime.now());
        startSchedule(LocalTime.of(02, 00));
    }

    private void startSchedule(LocalTime atTime) {
        this.scheduledExecutorService.scheduleWithFixedDelay(() -> {
                    System.out.println(Thread.currentThread().getName() +
                            " |  scheduleWithFixedDelay | " + LocalDateTime.now());
                    // or whatever you want
                }, calculateInitialDelayInSec(atTime),
                LocalTime.MAX.toSecondOfDay(),
                TimeUnit.SECONDS);
    }

    private long calculateInitialDelayInSec(LocalTime atTime) {
        int currSec = LocalTime.now().toSecondOfDay();
        int atSec = atTime.toSecondOfDay();
        return (currSec < atSec) ?
                atSec - currSec : (LocalTime.MAX.toSecondOfDay() + atSec - currSec);

    }


text:
Q: How to handle mongoose errors globaly As for now, I'm using mongoose middleware to handle Mongoose specific errors (validation, cast, ....).
I'm using the following code in all of my schemas:
schema.post('save', handleValidationError);
schema.post('findOneAndUpdate', handleValidationError);
schema.post(['findOne', 'deleteOne'], handleCastError);

Is there anyway to make this global in all schemas without repeating the code?
I tried to use plugins as the following but they don't get triggered if an error happens.
const errorsPlugin = (schema: any, _options: any): void => {
    schema.post('save', handleValidationError);
    schema.post('findOneAndUpdate', handleValidationError);
    schema.post(['findOne', 'deleteOne'], handleCastError);
};

const connection = await mongoConnect(url);
plugin(errorsPlugin);
logger.info(`MongoDB connected: ${connection.connection.name}`);

Edit 1: error handler function
const handleValidationError = (error: NodeJS.ErrnoException, _res: Response, next: (err?: Error) => void): void => {
    if (error.code?.toString() === '11000') {
        const { keyPattern, keyValue } = error as Error & {
            keyPattern: { [key: string]: number };
            keyValue: { [key: string]: string };
        };
        const key = Object.keys(keyPattern)[0];
        const value = Object.values(keyValue)[0];
        throw new DuplicatedKeyError(key as string, value as string);
    } else if (error instanceof mongooseError.ValidationError) {
        throw new ValidationError(error.errors);
    } else if (error instanceof mongooseError.CastError) {
        throw new CastError(error.kind, error.value);
    }
    next();
};

A: This is an interesting insight and a nice approach you are taking, to solving the problem globally for all schemas.
Looking at the documentation, it looks like you are 90% there. The only thing I can spot that differs with the documentation is how you are applying your plugin.
To apply the plugin to a single schema you should be making the following call:
// mySchema.js : the same file where you define your schema
mySchema.plugin(errorsPlugin);

To apply the plugin to all schemas in the project, you can use the global mongoose object:
mongoose.plugin(errorsPlugin)

The above call should happen before you create any models, for example with mongoose.model("MyModel", mySchema). If you are creating all your models in a single file, it could look like this:
// models.js
mongoose.plugin(errorsPlugin)
const User = mongoose.model('User', userSchema)
const Car = mongoose.model('Car', carSchema)
// etc.

However if you are co-locating the model creation with the schema definition, for example:
const userSchema = new Schema({...})
const User = mongoose.model('User', userSchema);

After, you should make the call before requiring/exporting any models at all so that the plugin statement is evaluated before the model files are executed. For example:
// models/User.ts
const userSchema = new Schema({...})
export const User = mongoose.model('User', userSchema)

// models/Car.ts
const carSchema = new Schema({...})
export const Car = mongoose.model('Car', carSchema)

// models/index.ts
// Register all Global Plugins
mongoose.plugin(errorsPlugin)

// Export all models after plugins have been registered
export * from  './User'
export * from './Car'

I hope this helps :)

A: You may consider this approach:
Create an ErrorResponse Class
class ErrorResponse extends Error {
  constructor(message, statusCode) {
    super(message)
    this.statusCode = statusCode
  }
}

Create an error handler middleware
const errorHandler = (err, req, res, next) => {
  let error     = { ...err }
  error.message = err.message

  // Validation error
  if (err.name === 'ValidatorError') {
    error = new ErrorResponse(Object.values(err.error).map(({ message }) => message), 400)
  }

  // Wrong ObjectId
  if (err.name === 'CastError') {
    error = new ErrorResponse(`Resource not found with id of ${err.value}`, 404)
  }

  // Duplicated field
  if (err.code === 11000) {
    error = new ErrorResponse('Duplicate field value entered', 400)
  }

  res
    .status(error.statusCode || 500)
    .json({ error: error.message || 'Internal Server Error' })
}

Change your controllers
try{
   //... you code ... //
} catch (err) {
   next(err)
}

Use middleware after defining your routes
app.use(errorHandler)

A: When any errors will be thrown from any where they will go to errorhandler(error.js) from their they will return to front-side and we can handle any kind of error using any custom messages or status codes with below method.
app.js
// your server(app.js code)
// add bellow line to your app.js
const errorhandler = require("./Middleware/error");
app.use(errorhandler);

Middleware/error.js
const { giveresponse } = require("../helper/res_help");

const errorHandler = (err, req, res, next) => {
let message;
//Mongoose Bad Object
if (err.name === "CastError") {
    message = `Resourse not found`;
    //error = new ErrorResponse(message, 404);
}

//Mongoose Duplicate key
if (err.code === 11000) {
    message = "Duplicate field Value entered";
    //error = new ErrorResponse(message, 400);
}

//Mongoose validation Error
if (err.name === "ValidationError") {
    message = Object.values(err.errors).map((val) => val.message)[0];
    //error = new ErrorResponse(message, 400);
}

console.log(err);
return giveresponse(res, 201, false, message);
};

module.exports = errorHandler;

helper/res_help.js;
exports.giveresponse = function (
res,
status_code,
success,
message,
data = null
) {
var data = data == null ? {} : data;
data["success"] = success;
data["message"] = message;
data["status_code"] = status_code;
var json_to_send = { success: success, message: message, data: data };

return res.status(status_code).json(json_to_send);
};

your controllers //wrap your code in asyncHandler you want even need to use try-catch
const asyncHandler = require("../Middleware/async");
exports.login = asyncHandler(async (req, res) => {
     //your login api code
});

Middleware/async.js
const asyncHandler = (fn) => (req, res, next) =>
Promise.resolve(fn(req, res, next)).catch(next);

module.exports = asyncHandler;

A: You can define the middleware functions in a separate file and then import them into your schemas.
Create a new file errorHandler.js and declare your middleware functions inside:
const handleValidationError = (error, doc, next) => {
  if (error.name === 'ValidationError') {
    // handle validation error
  }
  next(error);
};

const handleCastError = (error, doc, next) => {
  if (error.name === 'CastError') {
    // handle cast error
  }
  next(error);
};

module.exports = {
  handleValidationError,
  handleCastError
};

Then import file in node.js schemas by:
const { handleValidationError, handleCastError } = require('./errorHandler');

const schema = new mongoose.Schema({
  // place your schema fields here
});

schema.post('save', handleValidationError);
schema.post('findOneAndUpdate', handleValidationError);
schema.post(['findOne', 'deleteOne'], handleCastError);

When you have multiple schemas in your application, defining the same middleware functions in every schema file can lead to code duplication and make your code harder to maintain. In such cases, it's a good practice to define the middleware functions in a separate file and import them into your schema files.

redpajama_set_name: RedPajamaStackExchange


text:
Q: apt-get: unmet dependencies, but dependencies can't install I'm in a spot where Ubuntu 12.04 LTS wants to do a dist-upgrade, but I can't do anything because /boot is full.
~$ df -h
/dev/sda1                               228M  227M     0 100% /boot

I want to remove old linux kernels, using apt-get autoremove, but I can't, since I have unmet dependencies.
~$ sudo apt-get autoremove
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these.
The following packages have unmet dependencies:
 libc6-dev : Depends: libc6 (= 2.15-0ubuntu10.9) but 2.15-0ubuntu10.11 is installed
             Depends: libc-dev-bin (= 2.15-0ubuntu10.9)
E: Unmet dependencies. Try using -f.

If I try to install the unmet dependencies using apt-get -f install, they fail, because /boot is full.
How do I get out of this loop where I can't free space on /boot and apt-get won't run?

A: I had to manually free up space in boot. Since apt-get was useless, I had to manually remove the files for the 2 oldest linux kernels. This is an example of what I ran to remove a single kernel.
Warning: Dangerous:
sudo rm /boot/vmlinuz-3.8.0-36-generic /boot/System.map-3.8.0-36-generic /boot/initrd-3.8.0-36-generic /boot/config-3.8.0-36-generic /boot/abi-3.8.0-36-generic

After freeing up space, apt-get -f install still failed, due to a half-installed kernel from the previously failed do-release-upgrade.
I ran do-release-upgrade again, and this time it was successful, except for the packages that were previously failing in apt-get. Here's an example of what was shown at the end of the upgrade:
dpkg: error processing package linux-generic-lts-trusty (--configure):
 dependency problems - leaving unconfigured
Errors were encountered while processing:
 linux-image-generic-lts-trusty
 libc6-dev:amd64
 linux-generic-lts-trusty

From here, I was able to run:
apt-get update
apt-get -f install
apt-get autoremove
apt-get upgrade

install fixed the dependency errors, and upgrade installed the latest kernel appropriately. I rebooted to test it out, and everything appears to be good.


text:
Q: 5 years later, is there something better than the "Fastest Possible C++ Delegates"? I know that the topic of "C++ delegates" has been done to death, and both http://www.codeproject.com and http://stackoverflow.com deeply cover the question.
Generally, it seems that Don Clugston's fastest possible delegate is the first choice for many people. There are a few other popular ones.
However, I noticed that most of those articles are old (around 2005) and many design choices seem to have been made taking in account old compilers like VC7.
I'm in need of a very fast delegate implementation for an audio application.
I still need it to be portable (Windows, Mac, Linux) but I only use modern compilers (VC9, the one in VS2008 SP1 and GCC 4.5.x).
My main criteria are:

*

*it must be fast!

*it must be forward-compatible with newer versions of the compilers. I have some doubts about that with Don's implementation because he explicitly states it's not standard-compliant.

*optionally, a KISS-syntax and ease-of-use is nice to have

*multicast would be nice, although I'm convinced it's really easy to build it around any delegate library

Furthermore, I don't really need exotic features. I just need the good old pointer-to-method thing. No need to support static methods, free functions or things like that.
As of today, what is the recommended approach? Still use Don's version?
Or is there a "community consensus" about another option?
I really don't want to use Boost.signal/signal2 because it's not acceptable in terms of performance. A dependency on QT is not acceptable as well.
Furthermore, I've seen some newer libraries while googling, like for example cpp-events but I couldn't find any feedback  from users, including on SO.

A: Update: An article with the complete source code and a more detailed discussion has been posted on The Code Project.
Well, the problem with pointers to methods is that they're not all the same size. So instead of storing pointers to methods directly, we need to "standardize" them so that they are of a constant size. This is what Don Clugston attempts to achieve in his Code Project article. He does so using intimate knowledge of the most popular compilers. I assert that it's possible to do it in "normal" C++ without requiring such knowledge.
Consider the following code:
void DoSomething(int)
{
}

void InvokeCallback(void (*callback)(int))
{
    callback(42);
}

int main()
{
    InvokeCallback(&DoSomething);
    return 0;
}

This is one way to implement a callback using a plain old function pointer. However, this doesn't work for methods in objects. Let's fix this:
class Foo
{
public:
    void DoSomething(int) {}

    static void DoSomethingWrapper(void* obj, int param)
    {
        static_cast<Foo*>(obj)->DoSomething(param);
    }
};

void InvokeCallback(void* instance, void (*callback)(void*, int))
{
    callback(instance, 42);
}

int main()
{
    Foo f;
    InvokeCallback(static_cast<void*>(&f), &Foo::DoSomethingWrapper);
    return 0;
}

Now, we have a system of callbacks that can work for both free and member functions. This, however, is clumsy and error-prone. However, there is a pattern - the use of a wrapper function to "forward" the static function call to a method call on the proper instance. We can use templates to help with this - let's try generalizing the wrapper function:
template<typename R, class T, typename A1, R (T::*Func)(A1)>
R Wrapper(void* o, A1 a1)
{
    return (static_cast<T*>(o)->*Func)(a1);

}

class Foo
{
public:
    void DoSomething(int) {}
};

void InvokeCallback(void* instance, void (*callback)(void*, int))
{
    callback(instance, 42);
}

int main()
{
    Foo f;
    InvokeCallback(static_cast<void*>(&f),
        &Wrapper<void, Foo, int, &Foo::DoSomething> );
    return 0;
}

This is still extremely clumsy, but at least now we don't have to write out a wrapper function every single time (at least for the 1 argument case). Another thing we can generalize is the fact that we're always passing a pointer to void*. Instead of passing it as two different values, why not put them together? And while we're doing that, why not generalize it as well? Hey, let's throw in an operator()() so we can call it like a function!
template<typename R, typename A1>
class Callback
{
public:
    typedef R (*FuncType)(void*, A1);

    Callback(void* o, FuncType f) : obj(o), func(f) {}
    R operator()(A1 a1) const
    {
        return (*func)(obj, a1);
    }

private:
    void* obj;
    FuncType func;
};

template<typename R, class T, typename A1, R (T::*Func)(A1)>
R Wrapper(void* o, A1 a1)
{
    return (static_cast<T*>(o)->*Func)(a1);

}

class Foo
{
public:
    void DoSomething(int) {}
};

void InvokeCallback(Callback<void, int> callback)
{
    callback(42);
}

int main()
{
    Foo f;
    Callback<void, int> cb(static_cast<void*>(&f),
        &Wrapper<void, Foo, int, &Foo::DoSomething>);
    InvokeCallback(cb);
    return 0;
}

We're making progress! But now our problem is the fact that the syntax is absolutely horrible. The syntax appears redundant; can't the compiler figure out the types from the pointer to method itself? Unfortunately no, but we can help it along. Remember that a compiler can deduce types via template argument deduction in a function call. So why don't we start with that?
template<typename R, class T, typename A1>
void DeduceMemCallback(R (T::*)(A1)) {}

Inside the function, we know what R, T and A1 is. So what if we can construct a struct that can "hold" these types and return them from the function?
template<typename R, class T, typename A1>
struct DeduceMemCallbackTag
{
};

template<typename R, class T, typename A1>
DeduceMemCallbackTag2<R, T, A1> DeduceMemCallback(R (T::*)(A1))
{
    return DeduceMemCallbackTag<R, T, A1>();
}

And since DeduceMemCallbackTag knows about the types, why not put our wrapper function as a static function in it? And since the wrapper function is in it, why not put the code to construct our Callback object in it?
template<typename R, typename A1>
class Callback
{
public:
    typedef R (*FuncType)(void*, A1);

    Callback(void* o, FuncType f) : obj(o), func(f) {}
    R operator()(A1 a1) const
    {
        return (*func)(obj, a1);
    }

private:
    void* obj;
    FuncType func;
};

template<typename R, class T, typename A1>
struct DeduceMemCallbackTag
{
    template<R (T::*Func)(A1)>
    static R Wrapper(void* o, A1 a1)
    {
        return (static_cast<T*>(o)->*Func)(a1);
    }

    template<R (T::*Func)(A1)>
    inline static Callback<R, A1> Bind(T* o)
    {
        return Callback<R, A1>(o, &DeduceMemCallbackTag::Wrapper<Func>);
    }
};

template<typename R, class T, typename A1>
DeduceMemCallbackTag<R, T, A1> DeduceMemCallback(R (T::*)(A1))
{
    return DeduceMemCallbackTag<R, T, A1>();
}

The C++ standard allows us to call static functions on instances (!):
class Foo
{
public:
    void DoSomething(int) {}
};

void InvokeCallback(Callback<void, int> callback)
{
    callback(42);
}

int main()
{
    Foo f;
    InvokeCallback(
        DeduceMemCallback(&Foo::DoSomething)
        .Bind<&Foo::DoSomething>(&f)
    );
    return 0;
}

Still, it's a lengthy expression, but we can put that into a simple macro (!):
template<typename R, typename A1>
class Callback
{
public:
    typedef R (*FuncType)(void*, A1);

    Callback(void* o, FuncType f) : obj(o), func(f) {}
    R operator()(A1 a1) const
    {
        return (*func)(obj, a1);
    }

private:
    void* obj;
    FuncType func;
};

template<typename R, class T, typename A1>
struct DeduceMemCallbackTag
{
    template<R (T::*Func)(A1)>
    static R Wrapper(void* o, A1 a1)
    {
        return (static_cast<T*>(o)->*Func)(a1);
    }

    template<R (T::*Func)(A1)>
    inline static Callback<R, A1> Bind(T* o)
    {
        return Callback<R, A1>(o, &DeduceMemCallbackTag::Wrapper<Func>);
    }
};

template<typename R, class T, typename A1>
DeduceMemCallbackTag<R, T, A1> DeduceMemCallback(R (T::*)(A1))
{
    return DeduceMemCallbackTag<R, T, A1>();
}

#define BIND_MEM_CB(memFuncPtr, instancePtr) \
    (DeduceMemCallback(memFuncPtr).Bind<(memFuncPtr)>(instancePtr))

class Foo
{
public:
    void DoSomething(int) {}
};

void InvokeCallback(Callback<void, int> callback)
{
    callback(42);
}

int main()
{
    Foo f;
    InvokeCallback(BIND_MEM_CB(&Foo::DoSomething, &f));
    return 0;
}

We can enhance the Callback object by adding a safe bool. It's also a good idea to disable the equality operators since it's not possible to compare two Callback objects. Even better, is to use partial specialization to allow for a "preferred syntax". This gives us:
template<typename FuncSignature>
class Callback;

template<typename R, typename A1>
class Callback<R (A1)>
{
public:
    typedef R (*FuncType)(void*, A1);

    Callback() : obj(0), func(0) {}
    Callback(void* o, FuncType f) : obj(o), func(f) {}

    R operator()(A1 a1) const
    {
        return (*func)(obj, a1);
    }

    typedef void* Callback::*SafeBoolType;
    operator SafeBoolType() const
    {
        return func != 0? &Callback::obj : 0;
    }

    bool operator!() const
    {
        return func == 0;
    }

private:
    void* obj;
    FuncType func;
};

template<typename R, typename A1> // Undefined on purpose
void operator==(const Callback<R (A1)>&, const Callback<R (A1)>&);
template<typename R, typename A1>
void operator!=(const Callback<R (A1)>&, const Callback<R (A1)>&);

template<typename R, class T, typename A1>
struct DeduceMemCallbackTag
{
    template<R (T::*Func)(A1)>
    static R Wrapper(void* o, A1 a1)
    {
        return (static_cast<T*>(o)->*Func)(a1);
    }

    template<R (T::*Func)(A1)>
    inline static Callback<R (A1)> Bind(T* o)
    {
        return Callback<R (A1)>(o, &DeduceMemCallbackTag::Wrapper<Func>);
    }
};

template<typename R, class T, typename A1>
DeduceMemCallbackTag<R, T, A1> DeduceMemCallback(R (T::*)(A1))
{
    return DeduceMemCallbackTag<R, T, A1>();
}

#define BIND_MEM_CB(memFuncPtr, instancePtr) \
    (DeduceMemCallback(memFuncPtr).Bind<(memFuncPtr)>(instancePtr))

Usage example:
class Foo
{
public:
    float DoSomething(int n) { return n / 100.0f; }
};

float InvokeCallback(int n, Callback<float (int)> callback)
{
    if(callback) { return callback(n); }
    return 0.0f;
}

int main()
{
    Foo f;
    float result = InvokeCallback(97, BIND_MEM_CB(&Foo::DoSomething, &f));
    // result == 0.97
    return 0;
}

I have tested this on the Visual C++ compiler (version 15.00.30729.01, the one that comes with VS 2008), and you do need a rather recent compiler to use the code. By inspection of the disassembly, the compiler was able to optimize away the wrapper function and the DeduceMemCallback call, reducing down to simple pointer assignments.
It's simple to use for both sides of the callback, and uses only (what I believe to be) standard C++. The code I've shown above works for member functions with 1 argument, but can be generalized to more arguments. It can also be further generalized by allowing support for static functions.
Note that the Callback object requires no heap allocation - they are of a constant size thanks to this "standardization" procedure. Because of this, it's possible to have a Callback object be a member of larger class, since it has a default constructor. It is also assignable (the compiler generated copy assignment functions are sufficient). It is also typesafe, thanks to the templates.

A: I wanted to follow off of @Insilico's answer with a bit of my own stuff.
Before I had stumbled upon this answer, I was trying to figure out fast callbacks as well that incurred no overhead and were uniquely comparable / identified by function signature only. What I ended up creating - with some serious help from Klingons Who Happened To Be at a BBQ - works for all function types (except Lambdas, unless you store the Lambda, but don't try it because it's really difficult and hard to do and may result in a robot proving to you how difficult it is and making you eat the shit for it). Thanks to @sehe, @nixeagle, @StackedCrooked, @CatPlusPlus, @Xeo, @DeadMG and of course @Insilico for the help in creating the event system. Feel free to use as you desire.
Anyway, an example is up on ideone, but the source code is also here for your use (because, since Liveworkspace went down, I don't trust them shady compiling services. Who knows when ideone will go down?!). I hope this is useful for somebody who's not busy Lambda/Function-objecting the world to pieces:
IMPORTANT NOTE: As of right now (28/11/2012, 9:35 PM) This variadic version will not work with the Microsoft VC++ 2012 November CTP (Milan). If you want to use it with that, you will have to get rid of all the variadic stuff and explicitly enumerate the number of arguments (and possibly template-specialize the 1-argument type for Event for void) to make it work. It's a pain, and I could only manage to write it out for 4 arguments before I got tired (and decided that passing more than 4 arguments was a bit of a stretch).
Source Example
Source:
#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>

template<typename TFuncSignature>
class Callback;

template<typename R, typename... Args>
class Callback<R(Args...)> {
public:
        typedef R(*TFunc)(void*, Args...);

        Callback() : obj(0), func(0) {}
        Callback(void* o, TFunc f) : obj(o), func(f) {}

        R operator()(Args... a) const {
                return (*func)(obj, std::forward<Args>(a)...);
        }
        typedef void* Callback::*SafeBoolType;
        operator SafeBoolType() const {
                return func? &Callback::obj : 0;
        }
        bool operator!() const {
                return func == 0;
        }
        bool operator== (const Callback<R (Args...)>& right) const {
                return obj == right.obj && func == right.func;
        }
        bool operator!= (const Callback<R (Args...)>& right) const {
                return obj != right.obj || func != right.func;
        }
private:
        void* obj;
        TFunc func;
};

namespace detail {
        template<typename R, class T, typename... Args>
        struct DeduceConstMemCallback {
                template<R(T::*Func)(Args...) const> inline static Callback<R(Args...)> Bind(T* o) {
                        struct _ { static R wrapper(void* o, Args... a) { return (static_cast<T*>(o)->*Func)(std::forward<Args>(a)...); } };
                        return Callback<R(Args...)>(o, (R(*)(void*, Args...)) _::wrapper);
                }
        };

        template<typename R, class T, typename... Args>
    struct DeduceMemCallback {
                template<R(T::*Func)(Args...)> inline static Callback<R(Args...)> Bind(T* o) {
                        struct _ { static R wrapper(void* o, Args... a) { return (static_cast<T*>(o)->*Func)(std::forward<Args>(a)...); } };
                        return Callback<R(Args...)>(o, (R(*)(void*, Args...)) _::wrapper);
                }
        };

        template<typename R, typename... Args>
        struct DeduceStaticCallback {
                template<R(*Func)(Args...)> inline static Callback<R(Args...)> Bind() {
                        struct _ { static R wrapper(void*, Args... a) { return (*Func)(std::forward<Args>(a)...); } };
                        return Callback<R(Args...)>(0, (R(*)(void*, Args...)) _::wrapper);
                }
        };
}

template<typename R, class T, typename... Args>
detail::DeduceConstMemCallback<R, T, Args...> DeduceCallback(R(T::*)(Args...) const) {
    return detail::DeduceConstMemCallback<R, T, Args...>();
}

template<typename R, class T, typename... Args>
detail::DeduceMemCallback<R, T, Args...> DeduceCallback(R(T::*)(Args...)) {
        return detail::DeduceMemCallback<R, T, Args...>();
}

template<typename R, typename... Args>
detail::DeduceStaticCallback<R, Args...> DeduceCallback(R(*)(Args...)) {
        return detail::DeduceStaticCallback<R, Args...>();
}

template <typename... T1> class Event {
public:
        typedef void(*TSignature)(T1...);
        typedef Callback<void(T1...)> TCallback;
        typedef std::vector<TCallback> InvocationTable;

protected:
        InvocationTable invocations;

public:
        const static int ExpectedFunctorCount = 2;

        Event() : invocations() {
                invocations.reserve(ExpectedFunctorCount);
        }

        template <void (* TFunc)(T1...)> void Add() {
                TCallback c = DeduceCallback(TFunc).template Bind<TFunc>();
                invocations.push_back(c);
        }

        template <typename T, void (T::* TFunc)(T1...)> void Add(T& object) {
                Add<T, TFunc>(&object);
        }

        template <typename T, void (T::* TFunc)(T1...)> void Add(T* object) {
                TCallback c = DeduceCallback(TFunc).template Bind<TFunc>(object);
                invocations.push_back(c);
        }

        template <typename T, void (T::* TFunc)(T1...) const> void Add(T& object) {
                Add<T, TFunc>(&object);
        }

        template <typename T, void (T::* TFunc)(T1...) const> void Add(T* object) {
                TCallback c = DeduceCallback(TFunc).template Bind<TFunc>(object);
                invocations.push_back(c);
        }

        void Invoke(T1... t1) {
                for(size_t i = 0; i < invocations.size() ; ++i) invocations[i](std::forward<T1>(t1)...);
        }

        void operator()(T1... t1) {
                Invoke(std::forward<T1>(t1)...);
        }

        size_t InvocationCount() { return invocations.size(); }

        template <void (* TFunc)(T1...)> bool Remove ()
        { return Remove (DeduceCallback(TFunc).template Bind<TFunc>()); }
        template <typename T, void (T::* TFunc)(T1...)> bool Remove (T& object)
        { return Remove <T, TFunc>(&object); }
        template <typename T, void (T::* TFunc)(T1...)> bool Remove (T* object)
        { return Remove (DeduceCallback(TFunc).template Bind<TFunc>(object)); }
        template <typename T, void (T::* TFunc)(T1...) const> bool Remove (T& object)
        { return Remove <T, TFunc>(&object); }
        template <typename T, void (T::* TFunc)(T1...) const> bool Remove (T* object)
        { return Remove (DeduceCallback(TFunc).template Bind<TFunc>(object)); }

protected:
        bool Remove( TCallback const& target ) {
                auto it = std::find(invocations.begin(), invocations.end(), target);
                if (it == invocations.end())
                        return false;
                invocations.erase(it);
                return true;
        }
};


text:
Q: How to setup PdfSharp Controller I am receiving a error in my apiPdfsharpController. The report i am printing is pulling data from the Job class. The job class is pulling data from the Customer Class. The Customer Class Data is what is causing the exception. I did add a ViewModel for the Job, however I do not know if that needs to be used here. if so I do not know how to use it instead of the Job Class itself.

Exception Message :
  Object reference not set to an instance of an object.
StackTrace:
     at TexasExterior.Controllers.PdfController.Get(Nullable`1 id) in c:\Development\TexasExterior\TexasExterior\Controllers\PdfController.cs:line 92

apiPdfController:
 public string Get(int? id) // allow nullable parameter
    {
        if (!id.HasValue) // if null return an empty string
        {
            return string.Empty;
        }

        // your code :

        apiJobController adapter = new apiJobController();
        Job job = new Job();
        job = adapter.GetJob(id);
        if (job == null)
        {
            return string.Empty;
        }
        try
        {

            // Create a new PDF document
            PdfDocument document = new PdfDocument();
            document.Info.Title = "Created with PDFsharp";

            // Create an empty page
            PdfPage page = document.AddPage();
            page.Size = PageSize.Letter;
            // Get an XGraphics object for drawing
            XGraphics gfx = XGraphics.FromPdfPage(page);
            XPen pen = new XPen(XColors.Black, Math.PI);
            //XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always);

            // Create a font
            XFont HeadingFont = new XFont("Times New Roman", 20, XFontStyle.Bold);
            XFont BodyFont = new XFont("Times New Roman", 12);
            // Draw the text

            gfx.DrawString("Date : ", BodyFont, XBrushes.Black,
              new XRect(127, 120, page.Width, page.Height),
              XStringFormats.TopLeft);

            gfx.DrawString(job.JobContractDate.ToString(), BodyFont, XBrushes.Black,
              new XRect(160, 120, page.Width, page.Height),
              XStringFormats.TopLeft);

            gfx.DrawString("Job Number : ", BodyFont, XBrushes.Black,
              new XRect(90, 140, page.Width, page.Height),
              XStringFormats.TopLeft);

            gfx.DrawString(job.JobNumber.ToString(), BodyFont, XBrushes.Black,
             new XRect(160, 140, page.Width, page.Height),
             XStringFormats.TopLeft);

            gfx.DrawString("Job Name", BodyFont, XBrushes.Black,
              new XRect(100, 160, page.Width, page.Height),
              XStringFormats.TopLeft);

            gfx.DrawString(job.JobName, BodyFont, XBrushes.Black,
             new XRect(160, 160, page.Width, page.Height),
             XStringFormats.TopLeft);

            gfx.DrawString("Customer : ", BodyFont, XBrushes.Black,
              new XRect(102, 180, page.Width, page.Height),
              XStringFormats.TopLeft);

            gfx.DrawString(job.Customer.CustomerName, BodyFont, XBrushes.Black,
              new XRect(160, 180, page.Width, page.Height),
              XStringFormats.TopLeft);

            gfx.DrawString(job.Customer.CustomerAddress, BodyFont, XBrushes.Black,
              new XRect(160, 195, page.Width, page.Height),
              XStringFormats.TopLeft);

            gfx.DrawString(job.Customer.CustomerCity + job.Customer.CustomerState + job.Customer.CustomerZipcode.ToString(), BodyFont, XBrushes.Black,
              new XRect(160, 210, page.Width, page.Height),
              XStringFormats.TopLeft);

   var dt = DateTime.Now.ToString("f").Replace('/', '-').Replace(':', '-');
            var filename = string.Format("{0}--{1}.pdf", job.JobName, dt);
            string path = Path.Combine(HttpContext.Current.Server.MapPath("~/JobSetupPdfs/"),    Path.GetFileName(filename));
            document.Save(path);

            // ...and start a viewer.
            Process.Start(path);
        }
        catch (Exception ex)
        {
            Debug.Print(ex.ToString());
        }
        return string.Empty;

JobViewModel
public class JobViewModel
{
    public int JobId { get; set; }
    public int JobNumber { get; set; }
    public string JobName { get; set; }
    public string JobDescription { get; set; }
    public int JobOriginalContract { get; set; }
    public DateTime? JobContractDate { get; set; }
    public DateTime? JobBillingDate { get; set; }
    public int JobTotalCO { get; set; }
    public int JobRevisedContract { get; set; }
    public int JobOriginalBudget { get; set; }
    public string JobBillingForm { get; set; }
    public string JobTESPM { get; set; }
    public string JobTESSuperintendent { get; set; }
    public string JobStatus { get; set; }
    public string JobMoreShit { get; set; }
    public bool JobTaxExempt { get; set; }
    public bool JobCertPayroll { get; set; }
    public int JobCost { get; set; }
    public int JobRemainingBudget { get; set; }
    public int JobProfit { get; set; }
    public int JobPercentage { get; set; }
    public int JobTotalBilled { get; set; }
    public int JobBalanceToBill { get; set; }
    public int JobPaidToDate { get; set; }
    public int JobBalanceDue { get; set; }
    public string JobAddress { get; set; }
    public string JobCity { get; set; }
    public string JobState { get; set; }
    public int JobZipcode { get; set; }
    public string JobCounty { get; set; }
    public Int64 JobPhoneNumber { get; set; }
    public Int64 JobFaxNumber { get; set; }
    public bool JobIsHidden { get; set; }

    public int JobRetainage { get; set; }
    public int JobMinWage { get; set; }
    public string JobInsProgram { get; set; }

    public int CustomerId { get; set; }

    //public int? GeoAreaId { get; set; }

    //public int? JobClassId { get; set; }

    //public int? JobTypeId { get; set; }

}

apiJobController
 // GET api/<controller>/5
    public Job GetJob(int? id)
    {
        using (var context = new ApplicationDbContext())
        {
            Job model = new Job();
            model = context.Jobs.Where(j => j.JobId == id).FirstOrDefault();
            return model;
        }

    }

JobClass
  public class Job
{
    public int JobId { get; set; }
    public int JobNumber { get; set; }
    public string JobName { get; set; }
    public string JobDescription { get; set; }
    public int JobOriginalContract { get; set; }
    public DateTime? JobContractDate { get; set; }
    public DateTime? JobBillingDate { get; set; }
    public int JobTotalCO { get; set; }
    public int JobRevisedContract { get; set; }
    public int JobOriginalBudget { get; set; }
    public string JobBillingForm { get; set; }
    public string JobTESPM { get; set; }
    public string JobTESSuperintendent { get; set; }
    public string JobStatus { get; set; }
    public string JobMoreShit { get; set; }
    public bool JobTaxExempt { get; set; }
    public bool JobCertPayroll { get; set; }
    public int JobCost { get; set; }
    public int JobRemainingBudget { get; set; }
    public int JobProfit { get; set; }
    public int JobPercentage { get; set; }
    public int JobTotalBilled { get; set; }
    public int JobBalanceToBill { get; set; }
    public int JobPaidToDate { get; set; }
    public int JobBalanceDue { get; set; }
    public string JobAddress { get; set; }
    public string JobCity { get; set; }
    public string JobState { get; set; }
    public int JobZipcode { get; set; }
    public string JobCounty { get; set; }
    public Int64 JobPhoneNumber { get; set; }
    public Int64 JobFaxNumber { get; set; }
    public bool JobIsHidden { get; set; }

    public int JobRetainage { get; set; }
    public int JobMinWage { get; set; }
    public string JobInsProgram { get; set; }

    public int CustomerId { get; set; }
    public virtual Customer Customer { get; set; }

    //public int? GeoAreaId { get; set; }
    //public virtual GeoArea GeoArea { get; set; }

    //public int? JobClassId { get; set; }
    //public virtual JobClass JobClass { get; set; }

    //public int? JobTypeId { get; set; }
    //public virtual JobType JobType { get; set; }

    public virtual ICollection<ChangeOrder> ChangeOrders { get; set; }

}

Update
Angular Controller
$scope.EmailPdf = function () {

   var id = $scope.currentItem.JobId
    $http.get('/api/Pdf/' + id).success(function () {
        $scope.PrintPreviewModal();
    });
}

View
                                    Number:
                                    <input ng-model="currentItem.JobNumber" type="text" name="JobNumber">
                                    <input ng-hide="true" ng-model="currentItem.JobContractDate" type="text" />
                                    Customer:
                                    <input stype="text" ng-model="currentItem.Customer.CustomerName"
                                           typeahead="customer.CustomerName for customer in customerArray | filter:$viewValue"
                                           placeholder="Enter Customer" typeahead-on-select="selectEditCustomer($item)">

                                    Status:
                                    <select ng-model="currentItem.JobStatus">
                                        <option value="" selected="selected">Select</option>
                                        <option value="Active">Active</option>
                                        <option value="InActive">InActive</option>
                                        <option value="Complete">Complete</option>
                                    </select>
                                    Address:
                                    <input disabled style="width:200px" ng-model="currentItem.Customer.CustomerAddress" type="text">

                                    Name:
                                    <inputng-model="currentItem.JobName" type="text">
                                    City:
                                    <input disabled style="width: 93px" ng-model="currentItem.Customer.CustomerCity" type="text">

                                    St:
                                    <input disabled style="width: 30px" ng-model="currentItem.Customer.CustomerState" type="text">

                                    Zip:
                                    <input disabled style="width: 44px" ng-model="currentItem.Customer.CustomerZipcode" type="text">

<inputng-click="EmailPdf(currentItem)" type="button" value="Email" />

A: The problem is that your Job object has a null Customer property. Change the GetJob function to retrieve it like this:
model = context
            .Jobs
            .Include("Customer") //This is the important addition
            .Where(j => j.JobId == id)
            .First();


text:
Q: Connect one JSON to another I've got these 2 JSON that share a field userId
This one:
{
    "oldest": "2019-01-24T00:00:00+00:00",
    "activities": [
        {
            "message": "Henrik didn't resist a guilty pleasure at Starbucks.",
            "amount": 2.5,
            "userId": 2,
            "timestamp": "2019-05-23T00:00:00+00:00"
        },
        {
            "message": "Johan made a roundup.",
            "amount": 0.32,
            "userId": 3,
            "timestamp": "2019-05-22T00:00:00+00:00"
        },
        {
            "message": "You didn't resist a guilty pleasure at Starbucks.",
            "amount": 15,
            "userId": 1,
            "timestamp": "2019-05-21T00:00:00+00:00"
        }
]

And this one:
[
    {
        "userId": 1,
        "displayName": "Mikael",
        "avatarUrl": "http://qapital-ios-testtask.herokuapp.com/avatars/mikael.jpg"
    },
    {
        "userId": 2,
        "displayName": "Henrik",
        "avatarUrl": "http://qapital-ios-testtask.herokuapp.com/avatars/henrik.jpg"
    },
    {
        "userId": 3,
        "displayName": "Johan",
        "avatarUrl": "http://qapital-ios-testtask.herokuapp.com/avatars/johan.jpg"
    },
    {
        "userId": 4,
        "displayName": "Erik",
        "avatarUrl": "http://qapital-ios-testtask.herokuapp.com/avatars/erik.jpg"
    },
    {
        "userId": 5,
        "displayName": "George",
        "avatarUrl": "http://qapital-ios-testtask.herokuapp.com/avatars/george.jpg"
    },
    {
        "userId": 6,
        "displayName": "Daniel",
        "avatarUrl": "http://qapital-ios-testtask.herokuapp.com/avatars/daniel.jpg"
    }
]

Now I have the first one sorted out like this:
struct Root: Decodable {
    var oldest: Date
    var activities: [Activity]
}

struct Activity: Decodable {
    var message: String
    var amount: Float
    var userId: Int
    var timestamp: Date
}

Notice that the userId var in Activity (1st JSON) also appears on the 2nd JSON. I'm using these structs to populate my TableViewController.
What I ultimately need is to have the avatar image show up next to the message and date label (check image). For this I think I would need to connect/relate (don't know the word for it) the 1st JSON with the 2nd JSON, correct me if I'm wrong. Would I also need another struct for User?
This is my networking code:
let userJSONURLString = "https://qapital-ios-testtask.herokuapp.com/users"
        let activitiesJSONURLString = "https://qapital-ios-testtask.herokuapp.com/activities?from=2016-05-23T00:00:00+00:00&to=2019-05-23T00:00:00+00:00"
        guard let userURL = URL(string: userJSONURLString) else { return }
        guard let activitiesURL = URL(string: activitiesJSONURLString) else { return }

        URLSession.shared.dataTask(with: activitiesURL) { (data, response, err) in
            // perhaps check err
            // also perhaps check response status 200 OK

            guard let data = data else { return }

            do {
                // Activities
                let decoder = JSONDecoder()
                decoder.dateDecodingStrategy = .iso8601
                let result = try decoder.decode(Root.self, from: data)
                self.activities = result.activities

                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            } catch {
                print("Error serializing json: ", error)
            }

        }.resume()

And this is my cellForRowAt (if you need it):
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ActivityCell", for: indexPath) as! MainTableViewCell
        let activity = activities[indexPath.row]

        // Amount
        cell.amountLabel.text = String(format: "$%.2f", activity.amount)

        // Message
        let formattedString = activity.message.htmlAttributedString().with(font:UIFont(name: "Helvetica Neue", size: 15)!)
        cell.descriptionLabel.attributedText = formattedString

        // Date
//        cell.dateLabel

        // Avatar

        return cell
    }

Updated code:
struct Activity: Decodable {
    var message: String
    var amount: Float
    var userId: Int
    var timestamp: Date
    var avatar : UIImage = UIImage(named: "user-icon-image-placeholder-300-grey.jpg")!
    private enum CodingKeys : String, CodingKey { case message, amount, userId, timestamp }
}

URLSession.shared.dataTask(with: activitiesURL) { (data, response, err) in
            guard let data = data else { return }
            do {
                // Activities
                let decoder = JSONDecoder()
                decoder.dateDecodingStrategy = .iso8601
                let result = try decoder.decode(Root.self, from: data)
                self.activities = result.activities

                URLSession.shared.dataTask(with: userURL) { (data, response, err) in
                    guard let data = data else { return }
                    do {
                        // Users
                        let usersJson = try JSONSerialization.jsonObject(with: data, options: [])
                        guard let jsonArray = usersJson as? [[String: Any]] else { return }

                        for dic in jsonArray {
                            guard let avatarUrl = dic["avatarUrl"] as? String else { return }
                            print(avatarUrl)
                        }

                    } catch {
                        print("Error serializing json: ", error)
                    }
                    }.resume()
            } catch {
                print("Error serializing json: ", error)
            }

            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }.resume()

A: *

*In the Activity struct add CodingKeys and an extra member for the avatar URL
struct Activity: Decodable {
    let message: String
    let amount: Float
    let userId: Int
    let timestamp: Date

    var avatar : URL = // some default URL to a placeholder image on disk

    private enum CodingKeys : String, CodingKey { case message, amount, userId, timestamp }
}

The purpose of the CodingKeys is that only the first 4 struct members are decoded.

*In the completion handler of the first data task add a second data task to load the user data.

*Decode the JSON as array of dictionaries with JSONSerialization.

*In a loop get the activity for the given userId and update the avatar URL.

*Then reload the table view.

*To load the avatar images you need a logic to download and cache the images asynchronously.


text:
Q: Update statement inserts a new row instead of updating My code should just update a single specific row in the table. I used a simple procedure to update a record in the current application as well and it runs without any problem except this case. Every time the query runs, it actually inserts a new row instead of just updating an existing:
So here is my c# code:
        try
        {
            command.Parameters.Clear();
            command.Parameters.AddRange(vars);
            command.CommandText = "Update" + tableName;

            conn.Open();
            command.ExecuteNonQuery();
            conn.Close();

            this.GetData(tableName);
        }
        catch
        {
            throw;
        }

And here is my SQL code (please ingore 'Alter Procedure' statement, I just wanted to get the core script of the procedure):
    ALTER procedure [dbo].[UpdateExpenditureItems]
    (@ID int,
    @Name nvarchar(50),
    @IsGroup bit,
    @Parent nvarchar(50),
    @Description nvarchar(50)
    )

    AS

    Begin

--a new inserted row seems to be a result of running IF statement rather than ELSE
    if @Parent != null
        begin
        declare @ParentID int

        set @ParentID = (select ID from ExpenditureItems where Name=@Parent);

        UPDATE ExpenditureItems SET Name =@Name, Parent =@ParentID, [Description] =@Description, IsGroup = @IsGroup WHERE ID=@ID;

        end
    else
        begin
        UPDATE ExpenditureItems SET Name =@Name, [Description] =@Description WHERE ID=@ID
        end
    end

I cannot post a screenshot because of the reputation limit...
Thanks in advance.

A:  @Parent != null

This is not how you check for null in SQL
Change it to:
 @Parent is not null

A: The reason was that current form was inherited from the other and when I pressed the OK button, base class's OK button click event was fired first and then the child.
Solution: either end up with running base class button click event OR use virtual and override to override the base class method.


text:
Q: Multimodal route analysis not yielding correct results I asked this question a while ago about a route in a multimodal network dataset not using all forms of transport available. While the answer worked at the time, I am now in a similar situation again.
My multimodal network dataset has three feature classes containing a single bus route, bus stops and streets. The bus route and streets have fields containing one way status and the amount of seconds it takes to traverse them. My data is basically the same as the tutorial data for ESRI's tutorial on multimodal datasets, except I have bus lines instead of metro lines.
I think my problem is with setting up the connectivity groups correctly. The bus route was created by tracing along the streets and splitting it at bus stops. The bus stops are snapped to the end points of each segment of the bus route, i.e. Stop 1 is snapped to the from_point of Segment 1 etc. The streets are not split at intersections.
In theory, a pedestrian should be able to walk from a side road into a main road to a bus stop, board a bus, travel along the route, exit the bus and continue walking around the streets. My connectivity settings are as follows:

I have been using ESRI's tutorial as the basis for my dataset, but according to this:

For example, two edges created from two distinct source feature classes can connect if they are in the same connectivity group. If they are in separate connectivity groups, the edges won't connect unless they are joined by a junction that participates in both connectivity groups.

This seems to imply that I only need one connectivity group. I have tried solving for a route using both setups, but I have gotten an error each time. The analysis settings:

A: This could be part of the problem

The streets are not split at intersections.

If they aren't split at intersections then

If they do not share any coincident endpoints or vertices, no
  connectivity policy will create a junction at the point of
  intersection. Street data for network datasets must be cleaned first
  so that either vertices or endpoints are present at all intended
  junctions.

So it would behave like the illustration below, which might not be what you're expecting. Streets that don't share vertices won't be connected.

Why do your ftr_roads have Any vertex connectivity by the way?
You might also want to read up about connectivity and designing the network datasets, too.


text:
Q: Material UI pagination changing color I am trying to do some pagination, which in theory is working but the colour of the outline and number are coming out black and my background is very dark so it took me a while to even realised it was working because I couldn't see it at first.
I am trying to change the colour of those parts (or at least the colour of the number) however, this is not working. I have tried to follow different suggestions (including <PaginationItem>) but none is doing the job.
Does any one has any suggestions? at what is wrong? Thank you in advance!
import React from 'react';
import Pagination from "@material-ui/lab/Pagination";
import { makeStyles } from '@material-ui/core/styles';

const useStyles = makeStyles((theme) => ({
    selected: {
        color:'#ffffff',
    },
}));

const Paginations = ({ scientistQuestions, paginate, scientistsPerPage }) => {
   const classes = useStyles();

   const pageNumbers = [];
   for (let i = 1; i <= Math.ceil(scientistQuestions / scientistsPerPage); i++) {
       pageNumbers.push(i)
   }
   console.log(pageNumbers)
   const handlePage = (e) => {
       paginate(Number(e.target.innerText));
   }

    return (
        <div>
            <Pagination  className={classes.root} count={3} variant="outlined" onClick={(e)=> handlePage(e)} color="primary"  />
        </div>
    );
}

export default Paginations;

A: First, you declared a class selected but used classes.root.
Second, assigning the style to root doesn't override the item's color. In order to do that, you need to use the child selector: .MuiPaginationItem-root (source)
const useStyles = makeStyles(() => ({
  ul: {
    "& .MuiPaginationItem-root": {
      color: "#fff"
    }
  }
}));

export default function BasicPagination() {
  const classes = useStyles();
  return <Pagination classes={{ ul: classes.ul }} count={10} />;
}

https://codesandbox.io/s/matreial-ui-pagination-item-style-ign5e?file=/demo.tsx

A: You can use CSS or SASS to change color.
.MuiPagination-root {
  button {
    color: red !important;
 }
}

A: Here's the updated version for anyone using the latest version of mui
MuiPagination: {
    styleOverrides: {
        root: {
            button: {
                color: '#fff',
            },
        },
    },
}


text:
Q: Do you think this is the right way to rename a django app? I read different threads and tutorials on renaming and migrating a Django app (How to rename a Django app and migrate data from an app to the other for instance), I also tried to use the django package called django-rename-app but it didn't work at all.
I'm going to explain the way I renamed my app in my development environment and I would like to know if you expect troubles, as apparently everything is working just as it did before so I'm considering doing the same in production.
Here are the steps I took inside my root project directory and my virtualenv activated, using Django 3.2:
Create the destination app

django-admin startapp app2

Copy these files and directories

cp app1/*.py app2/

mkdir app2/templates

mkdir app2/static

cp app1/templates app2/templates

in this case I had a sub-folder named after the app so I renamed it like this

mv app2/templates/app1 app2/templates/app2

cp app1/static app2/static

Models.py
Change the related_name attributes of all ForeignKeys in my new models.py and update all their references inside my views, admin, form and templates
Make sure your apps won't imported by the same name
Look for the instanciation of an AppConfig class inside your app directory and if you find something like this:
from django.apps import AppConfig

class AnunciosConfig(AppConfig):
    name = 'app1'

that's where you need to also change your app name from app1 to app2
Activate the new app
Add my app2 to the list of the enabled apps of settings.py
Delete __pycache__
Find and delete or empty all the __pycache__ directories in app2
Migrations
this will not work until all the overlapping bits are corrected, so this is how I tested everything was ok (it will not be aware of URLs problem at this stage)

python manage.py makemigrations

python manage.py migrate

Cloning data
Now I used the Django shell to migrate data from app1 to the app2

python manage.py shell

import app1

from app2.models import *

So I will have to use "app1.ModelName" to refer to the old app and simply "ModelName" to address the new app2 instances
Then I use the Models and QuerySet API to just create new objects in app2 with for loops for each app1 instances, with a corresponding app2 object that is saved (this needs be written individually and depends on each situation)
Deactivate the old app
Now I remove or comment out the old app1 reference in settings.py so that it is disabled
Rename the directory
At this point I needed to rename the app1/ directory to something unknown to Django

mv app1 app1_

Deal with the new errors
It seems some more errors appeared here with URLS and Views, so I had to just update app1 references to app2 until they disappeared
Delete Database table
Enter MySQL (in my case), and disable FOREIGN_KEY_CHECKS

USE yourowndjangodatabase;

SHOW TABLES;

SET FOREIGN_KEY_CHECKS=0;

so now I can delete them like this

DROP TABLE app1__yourfirstmodel;

DROP TABLE app1__yoursecondmodel;

and so on until none is left, then set the FOREIGN_KEY_CHECKS back to 1 so that it is enabled

SET FOREIGN_KEY_CHECKS=1;

Like I saw here Can't drop table: A foreign key constraint fails
CONCLUSION
And basically that was it, it worked perfectly for my development environment. I have a perfect copy of my previous app1 and web application that is just using app2 now.
I improvised so I'm not sure this is the right procedure but it worked so I would like to ask if you see any problem or suspect there will be issues in production.


text:
Q: Context Menu Not Firing on Right Click I have the following ListBox. This works great and when I left click on the TextBlock it opens the recent file. However, when I right click the context menu does not open, instead it acts like a left click and the command LoadSelectedFileCommand fires, opening the recent document. Below is the ListBox XAML:
<ListBox ItemsSource="{Binding RecentFiles, NotifyOnSourceUpdated=True, IsAsync=True, Mode=TwoWay}"
         ItemContainerStyle="{StaticResource MenuListBoxItem}"
         VerticalAlignment="Stretch"
         Grid.Row="6" >
    <ListBox.ItemTemplate>
        <DataTemplate DataType="{x:Type RecentObjects:RecentFile}">
            <StackPanel Orientation="Horizontal">
                <CheckBox IsChecked="{Binding IsPinned}"
                             Style="{StaticResource imageCheckBox}"
                   ToolTip="{Binding IsPinned, Converter={StaticResource BooleanToVariableStringConverter}}"
                             DataAccess:DocumentCheckBox.IsCheckedOnData="{DynamicResource Pinned}"
                             DataAccess:DocumentCheckBox.IsCheckedOffData="{DynamicResource UnPinned}"
                             AttachedCommand:CommandBehavior.Event="Click"
                             AttachedCommand:CommandBehavior.Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type MahAppsControls:MetroContentControl}}, Path=DataContext.UpdateRecentFilesCommand}" >
                </CheckBox>
                <TextBlock Text="{Binding FileName}"
                              Style="{StaticResource MenuTextBlock}"
                              ToolTip="{Binding FullFileName}"
                              AttachedCommand:CommandBehavior.Event="MouseDown"
                              AttachedCommand:CommandBehavior.Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type MahAppsControls:MetroContentControl}}, Path=DataContext.LoadSelectedFileCommand}"
                              AttachedCommand:CommandBehavior.CommandParameter="{Binding FullFileName}">
                    <TextBlock.ContextMenu>
                        <ContextMenu>
                            <MenuItem Header="Open Study" />
                            <MenuItem Header="Open Containing Folder" />
                            <MenuItem Header="Remove From List" />
                        </ContextMenu>
                    </TextBlock.ContextMenu>
                </TextBlock>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

My question is how can I get the context menu to fire on the right click and the command to open on the left click?
Thanks for your time.

A: If you only want the LoadSelectedFileCommand to run when the left mouse button is clicked you should use the UIElement.MouseLeftButtonDown Event instead.


text:
Q: Meaning of $\sim$ with a point? In a report, I wanted to write something like this:
For large $n$, we get
$$ x_n \sim \chi^2_p.$$
And a corrector in his corrections added a point on the $\sim$. I understand that the way I wrote it is considered wrong, because what I actually meant is that when $n$ tends to infinity, $x_n$ follows a chi-square distribution or that if $n$ is large, the distribution of $x_n$ is well approximated by a chi-square distribution. I assume $\dot{\sim}$ means "approximate the distribution well" but I have never seen this notation and I have searched a little bit but found nothing.
So what does $\dot{\sim}$ mean in this context if this notation even exists?


text:
Q: Using landmarks in routing directions for ArcGIS Network Analyst? I was wondering if there is a way to use a set of landmarks (in a point class or something) that will be included in the directions output for a Network Analyst route. So if there is a point (or building polygon for that matter) at a corner, the text would read "Turn right at 7-11, on to _____". I found this thread: http://forums.arcgis.com/threads/35424-Displaying-point-features-as-landmarks-on-Network-Analysis-route-direction-maps , but I don't necessarily want to attribute my route paths with building information, which is what I gathered this was doing. I'm using ArcGIS 10. Any suggestions?
Thanks,
eric

A: Landmarks are now a feature of Network Analyst in 10.1


text:
Q: Visual Studio not checking files into TFS from Workspace Mapping to Two TFS Servers I can successfully connect to my TFS server and check files out. However, the files will not check in. VS just sits on the 'Pending Changes' tab saying 'Checking in x items'.
When i view performance monitor, i can see that there is no network activity.
My workspace contains projects from two different TFS servers. Could this be the problem? It was working 2 days ago..

A: All good now. There were issues with TFS (which was out of my control).


text:
Q: How to get the subnet mask of my android device which acts as a hotspot? I want to broadcast from an android device which acts as a hotspot, but using 255.255.255.255 does not work as UDP broadcast in android. But 192.168.1.255 this broadcast address works. When I check the IP address of my device its shows 192.168.1.4.
Now how to calculate address 192.168.1.255 from this address?

A: Well, if you have the broadcasting worked out and only need to change the last byte of the address to 255, you can do the following:
String getBroadcastAddress( final String address ) throws UnknownHostException {
    InetAddress addr = InetAddress.getByName( address );
    if( InetAddress instanceof Inet4Address ) {
        byte[] bytes = addr.getAddress();
        bytes[3] = 255;
        return InetAddress.getByAddress( bytes ).getHostAddress();
     } else {
         ... deal with ipv6
     }
}

Pulling the broadcast address directly from the NetworkInterface, results in this code:
public static String getBroadcast() throws SocketException {
    System.setProperty("java.net.preferIPv4Stack", "true");
    for( Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements(); ) {
        NetworkInterface nif = interfaces.nextElement();
        if( !nif.isLoopback() ) {
            for( InterfaceAddress addr : nif.getInterfaceAddresses() ) {
                return addr.getBroadcast().toString().substring(1);
            }
        }
    }
    return null;
}

You may have to sift through the NetworkInterface to find the one corresponding to the internal ip.


text:
Q: how to Load PPT in silverlight I need to prepare proof-of-concept for a silverlight application. For that I need to load PPT in silverlight. I just need to load PPT in browser and allow the user to perform next, previous, stop and pause actions. Anybody can help out.

A: It may be that you need to convert the powerpoint slides to images first? then build a "player" in silverlight to show these slides?
Not sure if Office supports export to Images? (for a manual process) but you could print to PostScript and convert to images using GhostScript.


text:
Q: How to define properties conditionally according to the conditional types for typescript interfaces Suppose I have an existing typescript interface used in a codebase
interface example<condition extends true | false = false> {
  a: string;
  b: string;
  c: condition extends true ? string : number;
  // many other properties
}

Now I want to keep property a if condition is true, but replace property a with property d if condition is false, how can I do it?
Are there any easy ways like how javascript object can do with it like the following (has syntax error though)
interface example<condition extends true | false = false> {
  ...(condition extends true && {a: string});
  ...(condition extends false && {d: string});
  b: string;
  c: condition extends true ? string : number;
  // many other properties
}

A: You can use next type:
type Example<Condition extends boolean = false> = Condition extends true ? {
    a: string;
    b: string;
    c: string;
} : {
    d: string;
    b: string;
    c: number;
}

Playground
According to TS convention, you should use CamelCase for types and interfaces.
Also, true | false is just a boolean

A: Found a solution
type Example<Condition extends boolean = false> = {
    b: string;
    c: string;
    e: string;
    f: string;
    g: string;
    h: string;
    i: string;
} & (Condition extends true ? {
    a: string;
} : {
    d: string;
})

anyway possible to do like this by using interfaces?


text:
Q: PyQt Button clicked as soon as program ran Using Qt Designer, I have created a simple Dialogue box. I have added a submit button called self.pushButton. I keep having a problem that when I run the program, the button is automatically clicked. I am getting the program to print to the shell, "button clicked" and this appears as soon as the program is run.
from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName(_fromUtf8("Dialog"))
        Dialog.resize(880, 479)
        self.label = QtGui.QLabel(Dialog)
        self.label.setGeometry(QtCore.QRect(240, 10, 351, 81))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Rockwell Nova Light"))
        font.setPointSize(25)
        self.label.setFont(font)
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName(_fromUtf8("label"))
        self.label_2 = QtGui.QLabel(Dialog)
        self.label_2.setGeometry(QtCore.QRect(60, 50, 741, 101))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Rockwell Nova Light"))
        font.setPointSize(15)
        self.label_2.setFont(font)
        self.label_2.setAlignment(QtCore.Qt.AlignCenter)
        self.label_2.setObjectName(_fromUtf8("label_2"))
        self.label_3 = QtGui.QLabel(Dialog)
        self.label_3.setGeometry(QtCore.QRect(60, 100, 741, 101))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Rockwell Nova Light"))
        font.setPointSize(15)
        self.label_3.setFont(font)
        self.label_3.setAlignment(QtCore.Qt.AlignCenter)
        self.label_3.setObjectName(_fromUtf8("label_3"))
        self.comboBox = QtGui.QComboBox(Dialog)
        self.comboBox.setGeometry(QtCore.QRect(340, 260, 161, 51))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Rockwell Nova Light"))
        font.setPointSize(12)
        self.comboBox.setFont(font)
        self.comboBox.setObjectName(_fromUtf8("comboBox"))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.pushButton = QtGui.QPushButton(Dialog)
        self.pushButton.setGeometry(QtCore.QRect(714, 412, 121, 41))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Rockwell Nova Light"))
        font.setPointSize(14)
        self.pushButton.setFont(font)
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.label_4 = QtGui.QLabel(Dialog)
        self.label_4.setGeometry(QtCore.QRect(60, 160, 741, 101))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Rockwell Nova Light"))
        font.setPointSize(15)
        self.label_4.setFont(font)
        self.label_4.setAlignment(QtCore.Qt.AlignCenter)
        self.label_4.setObjectName(_fromUtf8("label_4"))

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

        self.home()
        self.click()

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
        self.label.setText(_translate("Dialog", "Welcome to PURA!", None))
        self.label_2.setText(_translate("Dialog", "This app is your revision partner, helping you learn throughout the day.", None))
        self.label_3.setText(_translate("Dialog", "To begin, first add a question below", None))
        self.comboBox.setItemText(0, _translate("Dialog", "Multiple Choice", None))
        self.comboBox.setItemText(1, _translate("Dialog", "True or False", None))
        self.comboBox.setItemText(2, _translate("Dialog", "Written Question", None))
        self.pushButton.setText(_translate("Dialog", "Submit", None))
        self.label_4.setText(_translate("Dialog", "Select the type of question you would like to make", None))

    def home(self):

        self.pushButton.clicked.connect(self.click)

    def click(self):
        print("button clicked")

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    Dialog = QtGui.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())

A: You have a call to your click function at "setupUi"(line 75) function which is called to setup your ui at the beginning. So remove the self.click() from there.


text:
Q: Rails 3 render partial from another controller (error: ActionView::MissingTemplate) I'm trying to include a login (username / password) in the header of my application.html.erb. I am getting this error:
Missing partial /login with {:handlers=>[:rjs, :builder, :rhtml, :erb, :rxml], :locale=>[:en, :en], :formats=>[:html]} in view paths "/app/views"

This is happening when I make this call in my application.html.erb:
<%= render '/login' %>

'/login' is defined in my routes.rb as:
match '/login' => "sessions#new", :as => "login"

UPDATE: here is my sessions controller:
class SessionsController < ApplicationController

  def create
    if user = User.authenticate(params[:email], params[:password])
        session[:user_id] = user.id
        user.last_login = Time.now
        user.save
        redirect_to root_path, :notice => "login successful"
      else
        flash.now[:alert] = "invalid login / password combination " # don't show pass + params[:password]
        #render :action => "new"
        redirect_to login_path, :notice => "wrong user pass"
      end
  end

  def destroy
    reset_session
      redirect_to root_path, :notice => "successfully logged out"
  end

end

I have seen in other posts that this can be due to not defining a variable in a controller action, but since this is a session, and it is in the application.html.erb (application_controller.rb), I'm not sure how to do this. Anybody know how to do this? Thanks!

A: <%= render "sessions/login", :@user => User.new %>
will render login partial of sessions view, i.e. '_login.html.erb' in views/sessions and instantiate @user to new user so that it can be referenced directly in the partial as :
form_for @user, :url => sessions_path do |f|
  f.text_field :email

A: Check your file extension in my case file extension was rhtml, I changed it into html.erb.
Now its working fine.
Note:
This file with rhtml extension was working fine in rails <= 3.0.10. But stopped working in rails 3.1.12. So I changed its extension as mentioned above.


text:
Q: hide/show elements on click JS I have three links on top, Logos (#logos), Business cards (#businesscards), Flyers (#flyers)
By default, "Logos" link is highlighted with content (#logos-container) showing.
When clicking "Business cards", Business cards content (#businesscards-container) will show with other content hidden.
When clicking "Flyers", Flyers (#flyers-container) content will show with others hidden.
This is my code:
[Javascript]

[html]

Logos

Business cards

Flyers

The default is working, but not when I click on other links. I tried adding e.preventDefault but no results. How should I go about this?
Thanks for any help.
EDIT: Resolved! Thank you.

A: you should set the default display on the php page for all the containers. I assume logos is the default display.

then the JavaScript will handle the show and hide of the elements

A: As you have mentioned that they are links, you need to prevent default behaviour,try do try this:
    $("#logos").click(function (e) {
        e.preventDefault();
        $("#businesscards-container").hide();
        $("#flyers-container").hide();
        $("#logos-container").show();
    });
    $("#businesscards").click(function (e) {
        e.preventDefault();
        $("#logos-container").hide();
        $("#flyers-container").hide();
        $("#businesscards-container").show();
    });
    $("#flyers").click(function (e) {
        e.preventDefault();
        $("#logos-container").hide();
        $("#businesscards-container").hide();
        $("#flyers-container").show();
    });

A: Here is the fixed solution - JSFiddle
#flyers-container {

    display: none;
}

#businesscards-container {

    display: none;
}

Initially just add display none to divs you wanna hide.. and waa laaa


text:
Q: Could not find module 'Data.Primitive.Ptr' Does anyone have any idea why I'm not able to use Data.Primitive! I get this error whenever I try to import it:
Main.hs:8:1: error:
    Could not find module 'Data.Primitive.Ptr'
    Use -v to see a list of the files searched for.
  |
8 | import Data.Primitive.Ptr
  | ^^^^^^^^^^^^^^^^^^^^^^^^^

I have the primitive module installed and even when I try to install it again (without --reinstall flag) I get:
Resolving dependencies...
All the requested packages are already installed:
primitive-0.7.1.0

A couple of points to add:

*

*Ubuntu 20.04.1 LTS

*GHC version 8.6.5

Any help would be appreciated.
EDIT:
I install the packages using cabal install primitive and run the code using ghc -c -O Main.hs
P.S. I'm also pretty sure that I've run the same code on my machine but I can't remember if I had a different version of Ubuntu and/or GHC installed.

A: Do cabal install --lib primitive. --lib is necessary for the libraries to be usable by GHCi and such.


text:
Q: how to remove text added in a modal from an object after closing it I'm a beginner and I'm trying to add random jokes to a modal from an object. Until now everything works. What I want now is to clear the modal after I click the close button so that every time I click "lets have a laugh..." a new joke will appear without having to refresh the page.
Other suggestions to make the code cleaner are welcome.
const JokesObject = {
joke1: {
    question: "what is the ultimate paradox",
    answer: "There is no absolute truth"
},
joke2: {
    question: "what turns coffee into code",
    answer: "A programmer"
  }
};

function jokie () {

const ListJokes = Object.keys(JokesObject);
let randomJoke = ListJokes[Math.floor(Math.random() * ListJokes.length)];
const joke = JokesObject[randomJoke];

const jokeModalQuestion = document.getElementById('joke');
const jokeModalAnswer = document.getElementById('answer');
const addJoke = document.createTextNode(joke.question);
const addAnswer = document.createTextNode(joke.answer);

jokeModalQuestion.appendChild(addJoke);

function answer () {
    jokeModalAnswer.appendChild(addAnswer);
 };

document.getElementById('giveAnswer').addEventListener('click', answer)
};

jokie();

const toggleModal = () => {
document.querySelector('.modal').classList.toggle('modal-hidden');
};

document.querySelector('.show-modal').addEventListener('click', toggleModal);

document.querySelector('.modal__close-bar').addEventListener('click', toggleModal);

A: To make that possible, you need to move your answer function outside the main function (jokie), and whenever you open your modal, you set a variable with the answer the current joke contains.
That way, when the answer button is clicked, it will always be filled with the currently selected joke.

Here are some suggestions to improve the quality of your code.
Please remember that beautiful code is subjective, some people might prefer a different way of doing things, but I think there's a general consensus about what "good" code looks like.
Use an array instead of an object
You are using an object when what you want is actually an array.
Instead of
const colors = { color1: 'yellow', color2: 'red' };
const firstColorKey = Object.keys(colors)[0];
const firstColor = colors[firstColorKey];

Do this
const colors = [ 'yellow', 'red' ];
const firstColor = colors[0];

Use better namings
Don't try to be fun when naming methods / variables. Instead of jokie, use setRandomJoke. Try to be as verbose as possible.
Think of functions as units of work
Instead of having a single function doing all the work, try to separate work into different units. For instance, your jokie function was doing two things: getting a random joke and filling the modal with the joke text. That can be decomposed into two different functions: getRandomJoke and fillJoke (again, remember function names should be as descriptive as possible).
Use consistent naming
If you are using a rule for, say, class selectors, keep it consistent. You are using giveAnswer, which uses camelCase, when other class selectors are using hyphen-case.
Plase your constants values outside the function
You are calling getElementById to get the DOM elements all the time, when only once should suffice. You can achieve that by placing the constants outside your function.
Use a code beautifier
To stop thinking about indentation, people nowadays use a tool to automatically format the code. Prettier is heavily used among Javscript devs https://prettier.io/
Look into BEM for naming CSS classes
BEM (or alternative frameworks / methodologies) is used to keep a consistent naming on CSS code. In your code, you are already using some of that by using __, but you can improve that by instead of using joke and answer class names, using modal__joke and modal__answer.

Code

const jokes = [
  {
    question: "what is the ultimate paradox",
    answer: "There is no absolute truth",
  },
  {
    question: "what turns coffee into code",
    answer: "A programmer",
  },
];

const jokeModalQuestion = document.getElementById("modal__joke");
const jokeModalAnswer = document.getElementById("modal__answer");
document.getElementById("answer").addEventListener("click", answer);
let currentAnswerTextNode;

function answer() {
  jokeModalAnswer.innerText = currentAnswerTextNode;
}

function getRandomJoke(jokeList) {
  return jokeList[Math.floor(Math.random() * jokeList.length)];
}

function fillJoke(joke) {
  currentAnswerTextNode = joke.answer;
  jokeModalQuestion.innerText = joke.question;
  jokeModalAnswer.innerText = "";
}

function showModal() {
  const joke = getRandomJoke(jokes);
  fillJoke(joke);
  document.querySelector(".modal").classList.remove("modal-hidden");
}

function hideModal() {
  document.querySelector(".modal").classList.add("modal-hidden");
}

document.querySelector(".show-modal").addEventListener("click", showModal);

document
  .querySelector(".modal__close-bar")
  .addEventListener("click", hideModal);
.modal-hidden {
  display: none
}
<button class="show-modal">Show Modal</button>

  <button class="modal__close-bar">Close Modal</button>

  <button id="answer">Answer</button>


text:
Q: How to make Ansible Dynamic Inventory work with Google Cloud Platform (Google Compute Engine), GCP I used Ansible to create a gce cluster following the guideline at: https://docs.ansible.com/ansible/latest/scenario_guides/guide_gce.html
And at the end of the GCE creations, I used the add_host Ansible module to register all instances in their corresponding groups. e.g. gce_master_ip
But then when I try to run the following tasks after the creation task, they would not work:
- name: Create redis on the master
  hosts: gce_master_ip
  connection: ssh
  become: True
  gather_facts: True
  vars_files:
    - gcp_vars/secrets/auth.yml
    - gcp_vars/machines.yml
  roles:
    - { role: redis, tags: ["redis"] }

Within the auth.yml file I already provided the service account email, path to the json credential file and the project id. But apparently that's not enough. I got errors like below:
UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: Permission denied (publickey).\r\n", "unreachable": true}

This a typical ssh username and credentials not permitted or not provided. In this case I would say I did not setup anything of the username and private key for the ssh connection that Ansible will use to do the connecting.
Is there anything I should do to make sure the corresponding credentials are provided to establish the connection?
During my search I think one question just briefly mentioned that you could use the gcloud compute ssh... command. But is there a way I could specify in Ansible to not using the classic ssh and use the gcloud one?

A: To have Ansible SSH into a GCE instance, you'll have to supply an SSH username and private key which corresponds to the the SSH configuration available on the instance.
So the question is: If you've just used the gcp_compute_instance Ansible module to create a fresh GCE instance, is there a convenient way to configure SSH on the instance without having to manually connect to the instance and do it yourself?
For this purpose, GCP provides a couple of ways to automate and manage key distribution for GCE instances.
For example, you could use the OS Login feature. To use OS Login with Ansible:

*

*When creating the instance using Ansible, Enable OS Login on the target instance by setting the "enable-oslogin" metadata field to "TRUE" via the metadata parameter.

*Make sure the Service Account attached to the instance that runs Ansible have both the roles/iam.serviceAccountUser and roles/compute.osLoginAdmin permissions.

*Either generate a new or choose an existing SSH keypair that will be deployed to the target instance.

*Upload the public key for use with OS Login: This can be done via gcloud compute os-login ssh-keys add --key-file [KEY_FILE_PATH] --ttl [EXPIRE_TIME] (where --ttl specifies how long you want this public key to be usable - for example, --ttl 1d will make it expire after 1 day)

*Configure Ansible to use the Service Account's user name and the private key which corresponds to the public key uploaded via the gcloud command. For example by overriding the ansible_user and ansible_ssh_private_key_file inventory parameters, or by passing --private-key and --user parameters to ansible-playbook.

The service account username is the username value returned by the gcloud command above.
Also, if you want to automatically set the enable-oslogin metadata field to "TRUE" across all instances in your GCP project, you can simply add a project-wide metadata entry. This can be done in the Cloud Console under "Compute Engine > Metadata".


text:
Q: Custom login procedure on Windows(10) Is there a way to create a custom login screen like Hello Windows, is there an api for such a thing?

A: Yes you can :

*

*Search for "regedit" in your Start menu and launch it.

*In the left-side panel, navigate to HKEY_LOCAL_MACHINE > Software > Microsoft > Windows > Current Version > Policies > System.

*In the right-hand panel, double-click "legalnoticecaption".

*In the "Value data" box, enter a title for your notice (for example, "ATTENTION" or "IF LOST, PLEASE CONTACT). Click OK.

*Double-click "legalnoticetext".
Enter a message containing your contact info, like your name, email address or phone number. If you're willing to provide a reward, mention that too. Click OK.


text:
Q: Is it possible to use "DDR Xccella Mode" when connecting an external RAM to the STM32? MCU: STM32H7A3ZIT6
RAM: APS12808L-3OBMx
This ram supports "DDR Xccela mode", where it transfers data on the rising and falling edge of the clock.
I'm fairly sure my MCU supports the standard octospi interface, but I'm not sure if I'll be able to get the double data rate. The MCU datasheet doesn't say anything about Xccela mode, but it does support some other modes "hyperram?" which I believe also transfers data on the rising and falling edge of the clock.

A: The short answer: maybe.
"Xccela" mode appears to be generally the same as Hyperbus, which that STM device supports (DDR clock, CMD+32 bit address / 6-byte header). However, they are different, and the Xccela consortium isn't saying exactly how. More about this below.
Check with ST apps engineering to ascertain if that Xccela part is supported. Failing that, ST specifically supports Hyperbus. So if you can't get an answer from them on Xccela, go with a Hyperbus part instead.
A business note. Hyperbus is promoted by Infineon (Cypress) and Spansion and is included in the JEDEC xSPI standard as an open document. Xccella is promoted by Micron, and while it is backward-compatable with JEDEC xSPI, it isn't included in the standard itself.
MORE: With some digging I did find at least a couple of differences between the protocols, from here: https://pdfserv.maximintegrated.com/en/an/ug6766.pdf

*

*Xccela supports byte-aligned data. Hyperbus does not (16-bit align only.)

*Hyperbus uses a differential clock pair (optional, but recommended for clocks above 100MHz.) Xccela clock is single-ended.


text:
Q: Javascript equivalent of Perl hash table comparisons I am relatively new to Javascript and have a need to do something that is easy for me to code up in Perl, but I cannot quite figure out the Javascript equivalent. Two arrays were populated with the contents of text windows named baseText and newText, where each window has very simple lines like A = 1, B = 5, etc.:-
function myJSComparator() {
    var baseEntries = stringAsLines(byId("baseText").value);
    var baseAllAppOptions = [];
    for (var i = 0; i < baseEntries.length; i++) {
        var fields = baseEntries[i].split("=");
        var baseAppOption = {optionName:fields[0],optionValue:fields[1]};
        baseAllAppOptions.push(baseAppOption);
    }
    var newEntries = stringAsLines(byId("newText").value);
    var newAllAppOptions = [];
    for (var i = 0; i < newEntries.length; i++) {
        var fields = newEntries[i].split("=");
        var newAppOption = {optionName:fields[0],optionValue:fields[1]};
        newAllAppOptions.push(newAppOption);
    }
}

How do I iterate over baseAllAppOptions and newAllAppOptions and output the following:-
1) A summary of only the optionName.fields that are the same in both baseAllAppOptions and newAllAppOptions, but whose corresponding optionValue.fields are different.
2) A summary of only the optionName.fields (and their corresponding optionValue.fields) that are in baseAllAppOptions, but not in newAllAppOptions.
3) A summary of only the optionName.fields (and their corresponding optionValue.fields) that are in the newAllAppOptions, but not in baseAllAppOptions.
I have three text windows waiting to receive the outputs of each line above. I plan to print to each text window like so...
    for (var i = 0; i < baseEntries.length; i++) {
        document.getElementById("baseChangeText").value += baseAllAppOptions[i].optionName + baseAllAppOptions[i].optionValue + String.fromCharCode(13);
    }

The above is just an example of how I would iterate over the array entries and print them out without doing any direct comparisons. But I need the format to be what is described in the document.getElementById line.
Any general guidance that can be shared would be much appreciated!
BTW, here is what I am working with:-
https://jsfiddle.net/e4bunLvh/57/
In each "Release #* App Option Defaults" window, just add something like A = 1 to both and then B = 2 in one and C = 3 in another.
Thanks!

A: If you convert each set of options to an object (equivalent to a hash in Perl), then it should be a simple matter of looping through the keys (and using Object.keys makes this simple) and simply testing for a difference in value, or defined-ness.
Example:

var getObjectWithContents = function(elementId) {
  return document.getElementById(elementId)
    .value
    .trim()
    .replace('\r\n', '\n') // replace Windows linebreaks to Unix
    .replace('\n\n', '\n') // replace double-linebreaks to single
    .split('\n').map(function(line) { // map into single key-value pairs
      var value = line.split('=');
      var key = value[0].trim();
      var val = value[1].trim();
      var o = {};
      o[key] = val;
      return o;
    }).reduce(function(o, p) { // reduce array of single key-value pairs to one object
      var key = Object.keys(p).shift();
      var val = p[key];
      o[key] = val;
      return o;
    }, {});
};

var getDifferenceByValue = function(optionsBase, optionsNew) {
  var difference = [];

  Object.keys(optionsBase).forEach(function(key) {
    var baseValue = optionsBase[key]; //
    var newValue = optionsNew[key];

    if (newValue !== undefined && baseValue !== newValue) {
      difference.push(key);
    }
  });

  return difference;
};

var getDifferenceByOption = function(a, b) {
  var difference = {};

  Object.keys(a).forEach(function(key) {
    if (b[key] === undefined) {
      difference[key] = a[key];
    }
  });

  return difference;
};

var outputToTextarea = function outputToTextarea(area, o, type) {
  var text = document.getElementById(area);
  text.value = Object.keys(o).map(function(key) {
    return key + '=' + o[key];
  }).join('\n');
};

var outputDiffByValue = function outputDiffByValue(array) {
  var text = document.getElementById('outputByValue');
  text.value = array.join('\n');
};

var getDiff = function getDiff() {
  var app1Defaults = getObjectWithContents('baseText');
  var app2Defaults = getObjectWithContents('newText');

  var stuffInBothWithDifferentValues = getDifferenceByValue(app1Defaults, app2Defaults);
  var stuffInBaseAndNotInNew = getDifferenceByOption(app1Defaults, app2Defaults);
  var stuffInNewAndNotInBase = getDifferenceByOption(app2Defaults, app1Defaults);

  outputDiffByValue(stuffInBothWithDifferentValues);
  outputToTextarea('diffBase', stuffInBaseAndNotInNew);
  outputToTextarea('diffNew', stuffInNewAndNotInBase);

  // console.log({
  //     stuffInBothWithDifferentValues,
  //     stuffInBaseAndNotInNew,
  //     stuffInNewAndNotInBase,
  // });
};

window.addEventListener('load', function() {
  var button = document.getElementById('logDiff');
  button.addEventListener('click', function(e) {
    getDiff();
    e.preventDefault();
    return false;
  }, false);
}, false);

  <textarea class="textbox" id="baseText" rows="5">
  a = 1
  b = 2
  c = 2
  f = 5
  </textarea>
  <textarea class="textbox" id="newText" rows="5">
  a = 0
  b = 1
  d = 3
  e = 4
  </textarea>
  <button id="logDiff">Get Differences</button>

Differences by Value

  <textarea class="textbox" id="outputByValue" rows="5"></textarea>

Stuff in Base (but not in New)

  <textarea class="textbox" id="diffBase" rows="5"></textarea>

Stuff in New (but not in Base)

  <textarea class="textbox" id="diffNew" rows="5"></textarea>


text:
Q: HTML newsletter image scaling I'm trying to finish development on an HTML newsletter.
The HTML is already responsive and working.
When trying to scale the images retrieved from WordPress posts via the_post_thumbnail, i have to use the following nonsensical code to make it work:
<img class="img_scale" <?php the_post_thumbnail(array(285,400));?>
as opposed to it's correct form:
<?php the_post_thumbnail(array (285,400), array('class' => 'img_scale')); ?>

*

*How is it possible the first line of code actually works ?

*How come the second line of code does not work ?