text:
Q: java8 functional interface to handle the callback I have a generic private method which does common tasks and is used by other methods. The generic method has if and else conditions to support other methods that are called. Example:
private void myGenericMethod(String name, int age){
  common task1;
  common task2;
  if(name!= null && name.length > 0){
     specific task 1;
     specific task 2;
  } else{
     specific task 3;
     specific task 4;
  }
  if(age > 18){
     specific task 1`;
     specific task 2`;
  }
}

I want to use Java 8 lambda and I have created a functional interface called Invoker with a invoke method.
public interface Invoker{
  public void invoke()
}

Now my generic method looks like this and the public method handles the invoke function callback appropriately:
private void myGenericMethod(Invoker invoker){
  common task1;
  common task2;
  invoker.invoke();
}

Is there a functional interface in the JDK that I can use instead of creating this interface by myself?

A: Package java.util.function does not contain a functional interface with a method that does not require any parameter and returns void. But you can use Runnable interface instead.
private void myGenericMethod(Runnable runnable){
    common task1;
    common task2;
    //consider checking if runnable != null to avoid NPE
    runnable.run();
}

Then the invocation would look pretty simple:
myGenericMethod(() -> {
    //do something fancy
    System.out.println("Hello, world!");
});

Other options
There are other functional interfaces you may be interested in, for example:

*

*Supplier<T> if you want to return a value of T without passing any parameters

*Function<T,R> if you want to pass a value of T and return a value of R

*Consumer<T> if you want to pass value T as a parameter and return void
Why there is no alternative for Runnable interface?
Using Runnable interface for a lambda that does not return nothing and does not expect any parameters may sound controversial for many programmers. Runnable was invented for running a code in a separate thread and many programmers identify this class with multithreading. Even documentation says:

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.

Someone already asked similar question 2 years ago and if you take a look at this comment and Brian Goetz's reaction to it you will understand that Java language designers came to a conclusion that there is no need to create another functional interface that mimics implementation of Runnable interface.

A: There is also the possibility to use Consumer<Void>. It could look like this
public void init(Consumer<Void> callback) {
    callback.accept(null);
}

init((Void) -> done());

A: I suggest to use Consumer as callback interface. Comparing it with the JavaScript language, callbacks are bound with a scope. Therefore, if you make use of Consumer interface then you can pass the scope as parameter to the function.
Ex:
public void startTracer(String tracerName, Event boundEvent) {
    executeOnTracer(tracer -> tracer.startTracer(tracerName, boundEvent));
}
...
private void executeOnTracer(Consumer<Tracer> callback) {
    TracerController tracer = null;
    if (isTracerActive()) {
        tracer = getTracer();
    }
    Optional.ofNullable(tracer).ifPresent(callback::accept);
}


text:
Q: Is it right to say this? Are the   sentences  given  below grammatically correct
How  many  is that ?
How  many  cars  is  that ?
How many  people  is that?
If  not   what  alternatives would you  suggest

A: Grammatically correct but semantically awkward without context.
P1: There are several people at the convention.
P2: How many people is that?
This is sort of sarcastic and demanding when I read it. A better way to say this would be How many people are there?
P1: There is a baker's dozen worth of donuts here.
P2: How many is that?
In this response the sentence is correct. The person is asking how many donuts are in a baker's dozen. It could be made more formal by saying how many donuts are in a baker's dozen?
P1: Our sales at the car lot showed we have sold 30% fewer cars this quarter.
P2: How many cars is that?
Again, P2 is asking for clarification. How many cars constitutes 30% of the sales of the previous quarter though it is informal. Perhaps a better way to say it would be How many fewer cars did we sell?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can dependency injection be implemented to windows library projects? Can dependency injection be implemented to windows library projects? Or this design pattern is not practiced in libraries?

A: You certainly can.
Microsoft for example does that with all their ASP.NET Core libraries. They all support dependency injection.
The important part for ease-of-use is to make sure the library knows how to wire-up the dependencies. For example, the Microsoft libraries all provide extension methods for the ServiceCollection, so I can write serviceCollection.AddLibraryName(); instead of having to add all the required classes myself.

A: Yes you can. you can do Asp.net core same as windows forms without other lib like autofac(if you want to use you can also)  and  .net with like https://autofac.org/ you can as much as you can register you services, repo, singletons.
    var builder = new ContainerBuilder();

// Register individual components
builder.RegisterInstance(new TaskRepository())
       .As<ITaskRepository>();
builder.RegisterType<TaskController>();
builder.Register(c => new LogManager(DateTime.Now))
       .As<ILogger>();

// Scan an assembly for components
builder.RegisterAssemblyTypes(myAssembly)
       .Where(t => t.Name.EndsWith("Repository"))
       .AsImplementedInterfaces();

var container = builder.Build();

UPDATE
    static class Program {
    private static Container container;

    [STAThread]
    static void Main() {

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Bootstrap();
        Application.Run(container.GetInstance<Form1>());
    }

    private static void Bootstrap() {
        // Create the container as usual.
        container = new Container();

        // Register your types, for instance:
        container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Singleton);
        container.Register<IUserContext, WinFormsUserContext>();
        container.Register<Form1>();

        // Optionally verify the container.
        container.Verify();
    }
}

And we can use like this.
   public partial class Form1 : Form {
    private readonly IUserRepository userRepository;
    private readonly IUserContext userContext;

    public Form1(IUserRepository userRepository, IUserContext userContext) {
        this.userRepository = userRepository;
        this.userContext = userContext;

        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e) {
        if (this.userContext.IsAdministrator) {
            this.userRepository.ControlSomeStuff();
        }
    }
}


text:
Q: Update date only if record updated with data modification I'm using Oracle JPA for my project. In my project, we receive file and insert or update (if any field value modified) the records in to database table.
There is a chances of receiving duplicate (already received) records without field value modifications.
My need is

*

*If the same record received without any change, date column should not be updated.

*If new record or same record with any modification, date column should update.

As an example
First insert:
Record to be inserted:
EmpID  |  Name  | Designation  | Salary
=========================================
00001  |  Raj   | Team Lead    |600000
00002  |  Kumar | Developer    |400000

Table after insert:
Emp ID | Name  | Designation | Salary | DATE
===========================================================
00001  | Raj   | Team Lead   | 600000 | 12-04-2018 01:00:00
00002  | Kumar | Developer   | 400000 | 12-04-2018 01:00:00

Second insert:
Record to be inserted:
EmpID  |  Name  | Designation      | Salary
==============================================
00001  |  Raj   | Team Lead        |600000
00002  |  Kumar | Senior Developer |500000

Table after insert/update:
Emp ID | Name  | Designation      | Salary | DATE
===========================================================
00001  | Raj   | Team Lead        | 600000 | 12-04-2018 01:00:00
00002  | Kumar | Senior Developer | 500000 | 13-04-2018 01:00:00

Here only send row date changed as it is only really modified.
Doing this validation in code is tedious task. Kindly say is there any possible solution.

A: You need a Listener to set current time
public class BaseEntityListener {

    @PreUpdate
    public void preUpdate(BaseEntity entity) {

        Date date = new Date();
        entity.setUpdateDate(date);
    }

}

Here is Model defination:
@SuppressWarnings("serial")
@MappedSuperclass
@EntityListeners(BaseEntityListener.class)
public class BaseEntity implements java.io.Serializable {

    @Basic(optional = false)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "updateDate")
    private Date updateDate;

And update entity use
        entityManager.merge(model);
        entityManager.flush();

updateDate would be updated when any column is changed. It won't be updated when no column is changed.


text:
Q: Fastest way to navigate to directories across varying revision trees within emacs I use Emacs and a revision tracker (perforce) for work-related things.
I have numerous (~10) different clients for Perforce that all have the same file structure. I would like to make generic commands to navigate to directories within these clients in Emacs.
However, the client paths are different. I want to make the navigation across directories be independent of the client name; instead, the client name should dynamically be determined.
For example, here are various paths to my clients:
/home/scratch/client1/hw/unit1/
/home/scratch2/client2/hw/unit2/
/home/scratch3/client3/hw/unit1/

As you can see, the path to each client varies, although the same structure is followed. Within each of these clients, the file structure is identical. So, each client's unit file will have the same structure (ie. ip/src/ or some equivalent path)
I see a lot of solutions for bookmarking directories to quickly jump to them, but I need something that works dynamically across all of my clients that have slightly different paths. Currently, if I use the bookmarks functionality, it will copy my whole client path to the directory, not a path based on the client I am currently in.
To me, that would mean I need something that dynamically determines the location of the client, and then shows the same bookmarked files within each client.
So, say I want the following three bookmarked directories to show based on the current client I am in:
/path/to/client/ip/src/bin
/path/to/client/ip/src/etc
/path/to/client/ip/src/inc

How can I do this in Emacs so that the client path (/path/to/client/) is dynamically figured out based on where I launched Emacs and then it appends the actual path within the client to the client path (ip/src/bin).
NOTE: I do have bash aliases to quickly navigate to directories independent of the client name. But I would like to minimize switching between Emacs and the command line as much as possible by finding a solution that works right inside of Emacs.

A: *

*Is the path to the current client available in an environment variable? If so then you can use that variable in what you type to find-file.  It will be expanded during completion.

*The directory where Emacs itself was invoked is the value of variable invocation-directory.  If your client location is easily determined from that ("client path (/path/to/client/) is dynamically figured out based on where I launched Emacs"), then you can define a command that reads a file (or directory) name in your client directory.
For #2, how is your "client path (/path/to/client/) ... dynamically figured out based on where [you] launched Emacs"?  If you show that code then the rest should be trivial.


text:
Q: Is there a naming convention for method that returns completely a brand new object? Is there a naming convention for method that returns completely a brand new object?
"Generate" ?  "Create" ?

A: It can be Create as @David suggested, or GetNew - like GetNewProduct().
I prefer GetNew, because Create is more used in factory methods, GetSomething for plain objects, and then GetNewSomething to emphasize that actually a new object is being created.

A: Bar bar Foo.barFactory();   is often one used.
if Bar is an interface, the exact Bar can be picked by Foo's barFactory,
https://en.wikipedia.org/wiki/Factory_method_pattern

A: There is any public Microsoft recommended convention for that.


text:
Q: Drying clothes with the sun's heat, without any air Will my wet clothes dry if I hang them under the sun, and if there is no air around the clothes? In other words, do I need both air and heat to dry wet clothes, or is heat alone (in the imagined absence of any air)  enough to dry wet clothes? Related question : will wet clothes dry with only the suns heat, but when placed in a vacuum? Please note - I am trying to dry my clothes differently on earth, and not in outer space.

A: I think when you say "no air" you mean "no wind"  In modern greek too "air" can  mean "wind" and and also the content of the atmosphere.
So if you hang clothes in the same sun but with no wind to supply convection, the clothes will try slower than when a wind is blowing, due to convection. Convection replaces the saturated air close to the clothes with drier air  and accelerates drying.
For "no air" meaning "vacuum" look at the other answers. In vacuum plus sun they will dry faster, because the higher temperature evaporates H2O faster. They will dry up quite well in the shadow in vacuum too, because vapor pressure is non existent in vacuum and H2O will evaporate as fast as the geometry of the clothes allows anyway.

A: Disclaimer before I get started:  A perfect vacuum is impossible.  As I answer your question, I will take your use of the word "vacuum" to mean "a chamber with an air pressure arbitrarily close to 0 Pa."  When I use the word "vacuum" in my response, I mean the same.
Your clothes don't need the air in order to dry, and in fact, will dry more quickly.
You've often heard that the freezing point and boiling point of water are 273 K (0 degrees C) and 373 K (100 degrees C) respectively, although that's somewhat sloppy language.  The reality is that the freezing point and boiling point of water are 273 K and 373 K at standard atmospheric pressure.  The phase of a substance is not only a function of its temperature, but also of the pressure being exerted on it.  In the case of water, by increasing the pressure on the water, you can keep the water in the liquid phase for temperatures well above water's normal boiling point.  Some nuclear power plants exploit this fact to keep its coolant in the liquid phase, even after it has been heated by the reactor.
But, the reverse is also true, which is what your question is really about.  By lowering the pressure on water below standard atmospheric pressure, you can "boil" your water at temperatures in which it would ordinarily remain a liquid.This videoshows room temperature water that is boiling, because it is inside a vacuum chamber.
For your hypothetical wet clothing in a vacuum, the water would rapidly evaporate from the clothing, due to the reasons you've stated above.  Of course, any heat that you were to also add to your clothing would also speed up the process, although it would likely be overkill.  Assuming your article of clothing is laid flat to maximize surface area, and you have a pretty good vacuum, the process would go pretty quickly, even at low temperatures.

A: I don't understand the difference between the first and the second question, but the answer is "No, you don't need air for the clothes to dry".
In fact, it will dry faster if in vacuum, because the water will start to boil in zero pressure, even if the temperature is not 100º C. In fact, at zero pressure, water cannot exist in liquid, but will evaporate if the temperature is above roughly 200 K (i.e. –73º C), and freeze if it's below.
This is what happens to comets. Comets are clumps of ice and dust. When they get close to the Sun, they start to evaporate (or sublimate, to be more precise), and the released gasses and ions is what we see as their tails.

A: I think:
Without air arround, you have some kind of a black body. Depending on the distance to the sun your body will reach a constant temperature. If this temperature is above the boiling point, you wet clothes will become dry. Because the gravitational attraction of your clothes is much smaller than the pressure of the water vapor. Thus the water molecules will be emitted.

A: No air means no vapor too. So without air your clothes will dry more easily, because the wetness will vaporize more easily.

A: Your clothes would dry very quickly in a vacuum, assuming that the temperature is still one that one would find on earth. This is because the water would boil out of your clothes. On earth normally, boiling takes a lot of heat energy. This is because of the air pressure. In your scenario there is no air pressure. so the water will boil easily.

A: Is it possible that when you mean an absence of air, you mean to say an absence of moving air? If so, then there is a difference to how fast clothes will dry.
If there is no moving air, then the only considerable means of heating up the clothes and the moisture on the clothes is the thermal radiation from the sun. The radiation heats up the moisture and it becomes water vapour.
This water vapour will either linger around the clothes, or it will slowly be transported away by natural convection currents, depending on the temperature of the surrounding air. Either way, water vapour is not moving away quickly, and, due to a higher concentration gradient of water vapour, you can expect some of the vapour to recondense onto the clothes.
On the other hand, if there is wind, the speed at which your clothes dry increases. This is because wind carries any newly formed water vapour away quickly, minimising the concentration gradient about the clothes.
In addition, the collision of air molecules with water on the clothes may have enough energy to drag the water molecules away into the air current.
The only downside to there being an air current is that is enforces forced convection between the clothes+moisture surface and the air current. The clothes and the moisture will be slightly warmer that its surroundings due to radiation from the sun. This heat is sapped slightly by the cooler convection currents, will allows less of the water to vaporise. This, however, is overshadowed by the other two mentioned effects.
So, wind dries things quicker than by still air.
Apologies if I misinterpreted the question.


text:
Q: How can i prevent the form from opening again? How can i prevent the form from opening again.I made my application and installed it, however when i click on the icon again the application open once again and so on if i clicked on the icon again, how can i prevent that ?

A: Scott Hanselman did a good post on doing this a while back - here's the link

A: Try Mutex. Here is a good article on the subject:
http://odetocode.com/Blogs/scott/archive/2004/08/20/401.aspx
[STAThread]
static void Main()
{
   using(Mutex mutex = new Mutex(false, "Global\\" + appGuid))
   {
      if(!mutex.WaitOne(0, false))
      {
         MessageBox.Show("Instance already running");
         return;
      }

      Application.Run(new Form1());
   }
}

A: You can do it by Checking list of Currently Running Processes.
If It is Duplicated, Kill Self.
This will prevent Multiple Instances.
   Process[] pArry = Process.GetProcesses();   //Get Currently Running Processes
   int Instance_Counter = 0; // To count No. of Instances

  foreach (Process p in pArry)
       {
          string ProcessName = p.ProcessName;
        //Match the Process Name with Current Process (i.e. Check Duplication )
       //If So Kill self
        if(ProcessName == Process.GetCurrentProcess().ProcessName)
         {
            Instance_Counter++;
        }
           }

    if(Instance_Counter>1)
    {
       //Show Error and Kill Yourself
    }

A: It's not the best way but fixed method of Swanand Purankar's as it mentioned before:
//I set Timer's interval to "250", it's personal
//Just don't forget to enable the timer
private void timer1_Tick(object sender, EventArgs e)
{
    var self = Process.GetCurrentProcess();
    foreach (var proc in Process.GetProcessesByName(self.ProcessName))
    {
        if (proc.Id != self.Id)
        {
            proc.Kill();
        }
    }
}

However with this way you can't set an error. If you want that:
private void Form1_Load(object sender, EventArgs e)
{
    if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
    {
        MessageBox.Show("Hey there opening multiple instances of this process is restricted!", "Error",
            MessageBoxButtons.OK, MessageBoxIcon.Error);
        this.Close();
    }
}

Still, the user can easily pass this by renaming the program. Using registry can help. But a hacker/developer still can get rid of this. Via using a process monitor.


text:
Q: Is there any method to calculate $\sin(x)$ and $\cos(x)$ without calculating $x$ if I know $\tan(x)$? For example, if I know $\tan(x)=1.2345$, is there any method to calculate the value of $\sin(x)$ and $\cos(x)$ without using $\tan(x)$ or calculating $x$ first?

A: It is not that difficult:
sin(x)² + cos(x)² = 1

so
(sin(x) / cos(x))² + 1 = 1/cos(x)²

so
tan(x)² + 1 = 1/cos(x)²

so
cos(x)² = 1/(tan(x)² + 1)

In Javascript:
var tanX = 1.2345;
var cosX = Math.sqrt(1/(tanX*tanX+1));

Refer to this list of trigonometric identities!

A: It is really a math question..
Think that $\tan(x)=\sin(x)/\cos(x)\implies (\tan(x)^2)(\cos(x)^2) = \sin(x)^2$ .
As $\cos(x)^2 = 1 - \sin(x)^2$:
$\tan(x)^2 - (\tan(x)^2)(\sin(x)^2) = \sin(x)^2$
Therefore,
$\sqrt{\frac{\tan(x)^2}{\tan(x)^2 + 1}} = \pm\sin(x)$


text:
Q: Managing References Among Multiple Projects I'm not sure it matters for this question but, in any event, I'm using TeXlipse as my latex editor and project management tool. Now, suppose one has two projects A and B that are built with separate output files, say, A.pdf and B.pdf. Further, suppose that theorems in B refer to theorems in A. Is there an established way to "link" these projects where the references in B to A resolve properly? For example, suppose that in project A on has the following:

\begin{theorem}\label{a_1}
...
\end{theorem}

And in project B one writes

Here in project A we note the result \ref{a_1}

Is there a way for the compiler to "find" the item labeled "a_1" and display the appropriate theorem number? If these are PDF's that live in the same directory,
I would also expect to be able to click on the link and be taken to the appropriate
place in the referenced document.

A: You should have a look at the xr package. Suppose you have two .tex files, a.tex and b.tex. Load the xr package in the preambles of both files. In a.tex, insert the instruction (after \usepackage{xr})
\externaldocument{b} % the extension .tex is assumed

and in b.tex, insert the instruction
\externaldocument{a}

As long as the labels used in the two files are unique, everything should compile smoothly. (Actually, be sure to compile both files at least twice, to let LaTeX resolve all cross-references. And, be sure not to delete the .aux files, as they will contain the information LaTeX needs to process the cross-references...) The manual of the xr package explains what to do if some of the labels are not unique.
By the way, the xr package doesn't cooperate smoothly with the hyperref package. If you want to combine them, you need to first load xr-hyper instead of xr, and then load hyperref. The file xr-hyper.sty is distributed with the hyperref package.


text:
Q: Permutation of roots for Galois group with six elements We know that $\mathbb{Q}(\sqrt[3]{2},i\sqrt{3})$ is the splitting field of $x^3-2$ over $\mathbb{Q}$, and $[\mathbb{Q}(\sqrt[3]{2},i\sqrt{3}):\mathbb{Q}]=6$.
Now, consider an element $\alpha$ in the Galois group $\mathrm{Gal}(\mathbb{Q}(\sqrt[3]{2},i\sqrt{3}):\mathbb{Q})$. We know that $\alpha$ fixes $\mathbb{Q}$, while permuting the three roots of $x^3-2$. There are six possible permutations.
Question: How can we know that all six in fact belong to the Galois group? (Maybe some of them is not an automorphism of $\mathbb{Q}(\sqrt[3]{2},i\sqrt{3})$.)

A: $\newcommand{\size}[1]{\lvert #1 \rvert}$By the definition of the splitting field you have
$$
E = \mathbb{Q}(\sqrt[3]{2},\sqrt{-3}) = \mathbb{Q}(r_{1}, r_{2}, r_{3}),
$$
where $r_{1}, r_{2}, r_{3}$ are the roots of $f = x^3-2$.
Thus an element $\alpha \in G = \mathrm{Gal}(E:\mathbb{Q})$ is completely determined by the permutation it induces on the set $\Omega = \{ r_{1}, r_{2}, r_{3} \}$.
(More formally, the map
$$
\Xi : G \to S_{\Omega}, \qquad \alpha \mapsto \alpha|_{\Omega}
$$
is an injective homormorphism.)
Now $E/\mathbb{Q}$ is a Galois extension, so $\size{G} = \size{E:\mathbb{Q}} = 6$.
Since $G$ has six elements, it must induce six distinct permutations of $\Omega$, that is, all possible ones.
(More formally, $\Xi$ is an injective map between finite sets of the same size, so it is also onto.)


text:
Q: How to print the value of tensorflow object after applying a conv-pool layer on it? After applying this on a tensorflow Variable, I am only able to get the shape of the object,
How to get the value of the variable after these layers?

def model_part2(a):
    #q=tf.global_variables_initializer()
    p=tf.keras.layers.Conv1D(192,1)(a)
    #print(p.eval())
    p=tf.keras.layers.ReLU()(p)
    p=tf.keras.layers.MaxPool1D(1,2)(p)
    p=tf.keras.layers.Conv1D(256,1)(p)
    p=tf.keras.layers.ReLU()(p)
    p=tf.keras.layers.MaxPool1D(1,2)(p)
    p=tf.keras.layers.Conv1D(512,1)(p)
    p=tf.keras.layers.ReLU()(p)
    p=tf.keras.layers.MaxPool1D(1,2)(p)
    return p

`

A: In Tensorflow Version 2.x, it is pretty straight forward. Working code is shown below:
import tensorflow as tf

a =tf.constant(1.0,shape=[128,8192,1])

def model_part2(a):
    #q=tf.global_variables_initializer()
    p=tf.keras.layers.Conv1D(192,1)(a)
    #print(p.eval())
    p=tf.keras.layers.ReLU()(p)
    p=tf.keras.layers.MaxPool1D(1,2)(p)
    p=tf.keras.layers.Conv1D(256,1)(p)
    p=tf.keras.layers.ReLU()(p)
    p=tf.keras.layers.MaxPool1D(1,2)(p)
    p=tf.keras.layers.Conv1D(512,1)(p)
    p=tf.keras.layers.ReLU()(p)
    p=tf.keras.layers.MaxPool1D(1,2)(p)
    return p

q = model_part2(a)

print(q)

Output of the above code is shown below:
tf.Tensor(
[[[0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  ...
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]]

 [[0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  ...
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]]

 [[0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  ...
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]]

 ...

 [[0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  ...
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]]

 [[0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  ...
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]]

 [[0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  ...
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]
  [0.06378555 0.00853285 0.03427356 ... 0.         0.         0.        ]]], shape=(128, 1024, 512), dtype=float32)


text:
Q: How to smoothly change x coordinate of an svg element? I want to change the x1 and x2 of my svg line in 2 seconds. I do nbot know how I can do this transition. Can you help me with it please? :)
Here is my svg element:
 <svg height="50" width="1400">
   <line x1="{{xValue}}" y1="{{yValue}}" x2="{{x2Value}}" y2="{{y2Value}}" style="stroke:rgb(255, 0, 0);stroke-width:2;transform: "></line>
</svg>

This is the code in my js (angular) is which I am first setting the initial values of the svg coordinates. and then I want to change them through the svgLineFunc function.
    $scope.xValue = 40;
    $scope.yValue = 15;
    $scope.x2Value = 140;
    $scope.y2Value = 15;

    $scope.svgLineFunc = function (newValue) {

        $scope.xValue = newValue;
        $scope.x2Value = newValue + 140;

    };

but I want this change to be done smoothly like it is done with the css transition!!!
Thanks in advance for your help.


text:
Q: SQL query GROUP BY colA and ORDER by ColB issue What I am trying to do is to do a Distinct on only 1 Column with Access.
Access is unfortunately limited and we have to use an aggregate function.
SELECT ColB, max(ColA), Max(ColC)...
FROM Table1
WHERE blabalba
GROUP BY ColB

the query is working fine but what I would need is to have the result ORDER BY ColA and I can't if I add ORDER BY ColA at the end, I get the exeption You tried to execute a query that does not include the specified expression 'CSR' as part of an aggregate function.
How can we have this query order by ColA?
Also I don't know if this one is possible but I would need for the results to have ColA in the first position so basically we do a kind of a DISTINCT on ColB only and we order by ColA
ColA            ColB          ColC
1                A              @
1                A              #
1                B              #
2                C              %
2                D              &
3                E              *
3                E              !
3                E              @
3                F              $

Results
ColA           ColB            ColC
1               A               @
1               B               #
2               C               %
2               D               &
3               E               *
3               F               $

Thank you!!

A: To order by ColA, could you try this query?
SELECT colb, maxcola, maxcolc
FROM (
  SELECT ColB, max(ColA) AS maxcola, Max(ColC) AS maxcolc
  FROM Table1
  WHERE blabalba
  GROUP BY ColB
) AS sub
ORDER BY maxcola;

Or, if that doesn't work in Access, could you save the first query as a View and then query from the view using an ORDER BY?


text:
Q: How can i add Autocomplete textbox changed event in MVC3 How can I add an MVC3 autocomplete textbox changed event?  Below is my code.
My view code

States Filter :

   @Html.TextBox("Statestxt")

   <input type="image" value="submit" src="../../Images/FilterBrowse.gif"
          alt="submit Button" />

My controller:
public ActionResult AutocompleteAsync(string term)
{
    var suggestions = from s in Adm.states
    select s.state_name;
    var namelist = suggestions.Where(n => n.ToLower().StartsWith(term.ToLower()));

    return Json(namelist, JsonRequestBehavior.AllowGet);
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult States(state stateModel, string _stateName,
    FormCollection formvalues)
{
   AdmDataContext Adm  = new AdmDataContext;

   if (Request.Form["Statestxt"] == null)
   {
      ViewBag.Error = "Enter State Name.";
      ViewData["name"] = false;

      return View();
    }
    else
    {
        _stateName = Request.Form["Statestxt"].ToString();
        var record = (from state in Adm.states
                      where state.state_name == _stateName
                      select state).Count();

        if (record == 0)
        {
           ViewBag.Error = "Enter Valid State Name.";

           return View();

        }

        var _Stateid = from state in Adm.states
                       where state.state_name == _stateName
                       select state;

        int StateId = (int)_Stateid.First().state_id;
        var state1 = am.FindUpcomingStates2(StateId).ToList();

        if (state1 != null)
        {
            ViewData["name"] = true;
            return View("States", state1);
        }

     }
}

I want to change the data after entering Statestext.  Where can I write the code for the Textbox changed event?
Thanks.

A: I take it you want to call a Javascript function when the user changes the text.  There's an overload for the Html.TextBox helper that you can use for this:
@Html.TextBox("Statestxt", "", new { onkeyup = "fnAjaxAutocomplete(this)" })

Then your handler Javascript method would look like this:
function fnAjaxAutocomplete(element)
{
    var ajaxUrl = '@Url.Action("AutocompleteAsync")' + '?text=' + element.value;
    $.get(ajaxUrl(function(suggestionsJson) {
        // handle JSON result here
    });
}


text:
Q: Have set up mongodb, mongoose etc but when I try and add something to the database it doesn't actually add it I'm using localhost and have all the modules set up correctly and I've checked that the database exists.  When I type in localhost:3000/pods/add?firstName='John' it's supposed to add it to the database, but for some reason it isn't working.
var express = require('express');
var _ = require('underscore');
var mongoose = require('mongoose');
var podStore = require('./lib/pod-handler.js');
var podsLibrary = require('./lib/pods-library.js');
var podList = [];

var mongoPort = 27017;
var app = express();
var port = 3000;
var router = express.Router();
var pods = podsLibrary.list();

mongoose.connect('mongodb://localhost:'+mongoPort+'/pods');

router.route('/').get(function(request, response) {
  //console.log('You hit an empty URL .. :(');
    response.status(503).send("Service Unavailable");
});

router.route('/lib').get(function(request, response) {
  //console.log('You hit an empty URL .. :(');
    response.status(200).send("Cool beans!");
});

router.route('/pods/list').get(function(request, response){
  if(!pods){
    return response.status(503).send("Service Unavailable");
  }
  return response.status(200).send(makeReadableList(pods));

  function makeReadableList(pods){
    var podsHtml = " ";
    _.each(pods, function(value, key){podsHtml = podsHtml + key});
    return podsHtml;
  }
});

router.route('/pods/add').post(function(request, response){
  if (!request.query){
    return response.status(400).send("Please give first name");
  }
  var payload = request.query;
  if (!payload.firstName){
    return response.status(400).send("give name");
  }
  podStore.save({
    firstName: payload.firstName,
    lastName: payload.lastName

  }, function(){
    return response.status(200).send(payload.firstName + " has been added!");
    var space = " ";
    _.each(pods, function(value, key) {
      key + space;
      return space + payload.firstName + payload.secondName;
    });
  });
});

router.route('/pods').get(function(request, response) {
  //console.log("We reached the POD page -- Yay! :D");
  response.status(200).send("Server unavailable");
});

app.use('/', router);
app.listen(port, function () {
    console.log('App listening on port %s', port);
});

I've checked over my code countless times and I can't seem to find the problem.
Here's the pod-handler file.
var PodDoc = require('../models/pods.js');

module.exports = {
  save: save
}

function save(pod, callback){
  var podToSave = new PodDoc();
  podToSave.firstName = pod.firstName;
  podToSave.lastName = pod.lastName;
  /*podToSave.skills = pod.skills;
  podToSave.avatarUrl = pod.avatarUrl;
  podToSave.address = {
    number: pod.address.number,
    lineOne: pod.address.lineOne,
    lineTwo: pod.address.lineTwo,
    postcode: pod.address.postcode
  }
  podToSave.phoneNumbers = {
    mobile: pod.phoneNumbers.mobile,
    landline: pod.phoneNumbers.landline
  }*/
  podToSave.save(function(err){
    if(err){

      console.log(err);
    } else {
      console.log("Working");
      callback();
    }
  })
}

A: There may be a typo error as in the url you are using port 300 where as the port configured for localhost is 3000.
When I type in localhost:300/pods/add?firstName='John'

A: When I type in localhost:3000/pods/add?firstName='John' it's supposed to add it to the database
If i understand correctly, you want to open this url in browser, and expect to have a record John in database.
Change router request type to GET, this
router.route('/pods/add').post(/*omitted*/);

to this
router.route('/pods/add').get(/*omitted*/);

Server is expecting POST request, but browser cannot handle it without FORM element or ajax request, browsers usually uses GET request, i mean when you open your url, it send GET request to server


text:
Q: How to Style Specific Rel Link with CSS I have a website where there is a table which lists my posts, and the categories are displayed next to them. I want to "display:none" on all the categories except one. The issue is they are all specific to a "rel" link. Let me show you an example of the code:

No Limit

So basically I'm trying to be able to grab that specific "No Limit" label in the CSS. This is as far as I got, but as of right now it's grabbing all the "rel" links, and I can't get it more specific.
td.col-categories a[rel="category tag"] {display:none;}


text:
Q: facebookredirect.axd not found error Need help on the below error message I got when I'm trying to authenticate using latest Facebook C# SDK.
Error Message I got is:-

The resource cannot be found.
  Description: HTTP 404. The resource
  you are looking for (or one of its
  dependencies) could have been removed,
  had its name changed, or is
  temporarily unavailable.  Please
  review the following URL and make sure
  that it is spelled correctly.
Requested URL:
  /WebSite17/facebookredirect.axd

Here's what I have in my default.aspx.cs file
protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            var settings = ConfigurationManager.GetSection("facebookSettings");
            var current = settings as IFacebookApplication;
        var auth = new CanvasAuthorizer { Permissions = new[] { "user_about_me" } };

        if (auth.Authorize())
        {
            var client = new FacebookClient();
            dynamic me = client.Get("me");
            string firstName = me.first_name;
            string lastName = me.last_name;
            string email = me.email;
            Response.Write("First Name: " + firstName + "
Last Name: " + lastName + "
Email: " + email + "
");
        }
        else
        {
            Response.Write("You didn't login to Facebook.");
        }
    }
    catch (Exception ex)
    {
        Response.Write("Exception Message: " + ex.Message);
    }
}

I have already setup the web.config file as per the Sample CSASPNETFacebookApp
What else I have done wrong? I've included the references of .NET 4.0 of Facebook.dll and Facebook.web.dll and the namespaces.
Please advice.
Thanks

A: For me this worked,
1) Two http handler tags in web.config, below goes in system.web
<httpHandlers>
  <add verb="*" path="facebookredirect.axd" type="Facebook.Web.FacebookAppRedirectHttpHandler, Facebook.Web"/>
</httpHandlers>

and this in system.webServer
<handlers>
 <add name="facebookredirect" verb="*" path="facebookredirect.axd" type="Facebook.Web.FacebookAppRedirectHttpHandler, Facebook.Web"/>
</handlers>

Ref: Facebook SDK 4.2.1 - http 404 error, after permissions 'allow'
2) I had to add the tag validateIntegratedModeConfiguration="false" to resolve the http 500 error generated after modifying as per point#1. This goes inside system.webServer
<validation validateIntegratedModeConfiguration="false"/>

Ref: facebookredirect.axd generates a 500 error
3) Add the relevant authorization and cancellation urls in the CanvasAuthorizer
var auth = new CanvasAuthorizer();
auth.ReturnUrlPath = "YOUR_AUTHORIZATION_SUCCESS_REDIRECT_URL_PATH";
auth.CancelUrlPath = "YOUR_AUTHORIZATION_CANCELLED_URL_PATH";

I am not sure if this is in time to help you, but, it might just help someone else.
Happy coding!


text:
Q: MQ JNDI exception if the qmanager jndi is defined in multiple tomcat context.xml I have 2 applications deployed in the same tomcat jvm. Each application have their own context.xml:
- app1.xml
- app2.xml
In each of the app*.xml, I have MQ jndi resource defined:
<!-- JMS configuration FOR MQSeries - The connection factory -->
 <Resource
      name="jms/JMSQueueConnectionFactory"
      auth="Container"
      type="com.ibm.mq.jms.MQQueueConnectionFactory"
      factory="com.ibm.mq.jms.MQQueueConnectionFactoryFactory"
      description="JMS Queue Connection Factory for sending messages"
      CCDTURL="file:///apps/mqm_opt/creds/AMQCLCHL_XA.TAB"
      QMGR="***Example***QM01***Example***" UCP="Y"/>

I dont have MQ or jms jars in any of my wars. They are on the MQ client installation. I have added then in the classpath using shared.loader of catalina.properties:
shared.loader=${catalina.home}/shared/*.jar,/opt/mqm/java/lib/*.jar

Each application with just fine when deployed separately. But when they are deployed together in the same jvm, I am getting a null pointer at startup of one of the applications:
Jul 29, 2015 6:15:14 PM org.apache.naming.NamingContext lookup
WARNING: Unexpected exception resolving reference
java.lang.NullPointerException
        at com.ibm.msg.client.jms.internal.JmsFactoryFactoryImpl.getInstance(JmsFactoryFactoryImpl.java:169)
        at com.ibm.msg.client.jms.admin.JmsConnectionFactoryImpl.setProviderFactory(JmsConnectionFactoryImpl.java:176)
        at com.ibm.mq.jms.MQConnectionFactory.<init>(MQConnectionFactory.java:286)
        at com.ibm.mq.jms.MQQueueConnectionFactory.<init>(MQQueueConnectionFactory.java:76)
        at com.ibm.mq.jms.MQQueueConnectionFactoryFactory.getObjectInstance(MQQueueConnectionFactoryFactory.java:73)
        at org.apache.naming.factory.ResourceFactory.getObjectInstance(ResourceFactory.java:141)
        at javax.naming.spi.NamingManager.getObjectInstance(Unknown Source)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:842)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:153)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:830)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:153)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:830)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:153)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:830)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:167)
        at org.apache.naming.SelectorContext.lookup(SelectorContext.java:156)
        at javax.naming.InitialContext.lookup(Unknown Source)
        at org.springframework.jndi.JndiTemplate$1.doInContext(JndiTemplate.java:154)
        at org.springframework.jndi.JndiTemplate.execute(JndiTemplate.java:87)
        at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:152)
        at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:178)
        at org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:95)
        at org.springframework.jndi.JndiObjectLocator.lookup(JndiObjectLocator.java:105)
        at org.springframework.jndi.JndiObjectFactoryBean.lookupWithFallback(JndiObjectFactoryBean.java:201)
        at org.springframework.jndi.JndiObjectFactoryBean.afterPropertiesSet(JndiObjectFactoryBean.java:187)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1545)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1483)

So The app1 works fine but the app2 fails with the above exception. I have generally noticed this kind of error is when we have class loading issues. But in this case, I am not able to figure out where the issue is. Any clue will help.
EDIT: After some testing I figured, if tomcat loads app1 first then both of the apps work fine. But if it pick app2 then there is a problem. It seems like app2 is loading MQ classes with a wrong class loader. Not sure why. I have checked the war. It does not contain the MQ classes.

A: Based on notes in http://tomcat.apache.org/tomcat-8.0-doc/jndi-resources-howto.html#Using_resources I would suggest the resource in TomCat
should be along these lines.
<Resource name="jms/MyJMSCF" auth="Container"
          type="com.ibm.mq.jms.MQConnectionFactory"
          factory="org.apache.naming.factory.BeanFactory"
          hostName="my.host.name"
          transportType="1"/>  <!-- 1 means client mode -->

The MQConnectionFactory should be a compatible bean-style object; there are lots of configuration options - full JavaDoc is
http://www-01.ibm.com/support/knowledgecenter/api/content/SSFKSJ_8.0.0/com.ibm.mq.javadoc.doc/WMQJMSClasses/com/ibm/mq/jms/MQConnectionFactory.html
The com.ibm.mq.jms.MQQueueConnectionFactoryFactory object is solely used by JNDI to re-inflate an  object store via the javax.naming.Referencable interface.

A: The last edit gave me the clue. Upon careful inspection, I realised I had some MQ jar/classes packaged in app2.war. That is why when app2.war loaded first, it would load using WebApp2 class loader and This class is not accessible by app1.war. That is why the app1 would fail to load.
While app1.war did not have any mq classes. So when app1 loads first, the MQ classes were loaded by System class loader which is accessible by both apps.
Solution obviously was removing mq jars from app2.war


text:
Q: If statement in Laravel Eloquent I have two Models which are joined through three id's to one 1 id. The model AdviceProtocol had three ids defined: threshold_category1_id, threshold_category2_id and threshold_category3_id. These are all three linked to id from the model Categories. The threshold_cateogry_id's can be a number linked to the categories.id, or null.
In my query, I need to go through three of the threshold_catogory_ids and if they are NOT NULL, retrieve the categories.name. The query that I have now:
$advicePreparationsQuery = AdviceProtocol::select(['advice_protocols.name', 'advice_protocols.category', 'questions.name AS question_name', 'categories.name as Category_Name','categories.name as Category_Name2'])
            ->join('questions', 'advice_protocols.user_goal_id', '=', 'questions.id')
            ->join('categories', function ($join)
            {
                $join->on('advice_protocols.threshold_category1_id', '=', 'categories.id')->orOn('advice_protocols.threshold_category2_id', '=', 'categories.id')->orOn('advice_protocols.threshold_category3_id', '=', 'categories.id');
            })

This query now returns the same category.name twice.
I have tried to look up how other people have solved this problem, but i couldn't find something accurate online.

A: I'd try three joins with three different alias and then grab the name for each category name of each different alias:
$advicePreparationsQuery = AdviceProtocol::select(['advice_protocols.name', 'advice_protocols.category', 'questions.name AS question_name', 'categories1.name as Category_Name','categories2.name as Category_Name2','categories3.name as Category_Name2'])
            ->join('questions', 'advice_protocols.user_goal_id', '=', 'questions.id')
            ->join('categories as categories1', 'advice_protocols.threshold_category1_id', '=', 'categories1.id')
            ->join('categories as categories2', 'advice_protocols.threshold_category2_id', '=', 'categories2.id')
            ->join('categories as categories3', 'advice_protocols.threshold_category3_id', '=', 'categories3.id');

A: Use group by name in query  ie ->groupBy('category.name')
$advicePreparationsQuery = AdviceProtocol::select(['advice_protocols.name', 'advice_protocols.category', 'questions.name AS question_name', 'categories.name as Category_Name','categories.name as Category_Name2'])
        ->join('questions', 'advice_protocols.user_goal_id', '=', 'questions.id')
        ->join('categories', function ($join)
        {
            $join->on('advice_protocols.threshold_category1_id', '=', 'categories.id')->orOn('advice_protocols.threshold_category2_id', '=', 'categories.id')->orOn('advice_protocols.threshold_category3_id', '=', 'categories.id');
        }
       ->groupBy('category.name'))


text:
Q: How do you make a prompt display what you are typing as dots I have recently started making a webpage and I would like some parts of it to be password protected. So I made some parts of it password protected. Now I would like my password not to be shown when I am typing it how would I do that in a javascript prompt?

A: The simple answer is that you can't , prompts do not support this feature, you can look at this.
However you could use Jquery or build your own modal/ dialog to emulate this functionality.
See the jQuery UI Dialog for ideas and examples.

A: Modern browsers (including IE10) allow for creating modals with custom content, so you can use that.
As for storing the password: while it's better to have it verified by an external server, in case of an offline application, it's quite OK to store it in the script/localStorage as long as it's properly hashed, so that retrieving it in plain text is time-consuming.


text:
Q: I need a function for C++ on a Mac like std::cin but with a timeout I have a Mac, so I don't have access to any windows.h functions, or any other windows libraries in C++. I am creating a game in C++. The controls of the game are the characters w,a,s,d. Currently I have the input method as std:cin. However, the problem is after the user types each character they must hit enter every time. Furthermore, the fact the std::cin does not timeout means that the user can essentially 'pause' the game to think about what move to make next (which ruins much of the fun of this game).
I need a function like std::cin but with a timeout of about .25 seconds. A function that will return as soon as the user types the character (without the need of the user hitting enter) would also work; but a function like std::cin with a timeout would be preferred. Please don't suggest window's library functions as I am again a Mac user using terminal.
Are there any standard c++ functions within the standard mac Libraries which will function equivalently to std::cin with a timeout of T that will run correctly in a Mac terminal?

A: Any reason you can't use int istream::get() ?
It's a blocking call though. I'm sure there is a better way to do it, but the quickest hack I can think of is to spawn a thread (just before calling get()) that waits for 0.25 secs and then writes some 'timeout char' say 't' to teh stream.

A: You can use the ncurses library, putting the terminal in cbreak() (non-blocking) mode, and disabling input delay with nodelay():
WINDOW *window = initscr();
cbreak();
nodelay(window, TRUE);

Then the getch() function will not block, returning ERR if no character is ready, so you can poll it in a loop and break when your timeout has been reached.
However, this may also require that you use ncurses for screen output, which may be a dealbreaker.


text:
Q: deferred ajax not working I am using deferred Ajax using jquery. On click event of button "TestAjax" i will call 2 WCF services. when they are finished loading i will perform some logic. My code is as below
this.TestAjax = function () {
        debugger;
        var flattened1;
        var flattened2;

        function callFirstService() {

            ViewModel.loadFirstService(1));

       }

        function callSecondService() {

            ViewModel.loadSecondService(2);
       }

        // Multiple Ajax Requests
       $.when(callFirstService(), callSecondService()).done(function () {

           console.log("now we are will start logic);

           // logic here

        });

};

The code for calling services in different view model which is as below
  this.loadFirstService = function (id) {

        var input =
            {
                Id: id

            };

        $.ajax({
            url: "../RestService/someService",
            type: "PUT",
            contentType: 'application/json',
            processData: false,
            data: JSON.stringify(input),
            error: function(XMLHttpRequest, textStatus, errorThrown) {

                alert(errorThrown);
            },

            success: function(allData) {
                var test = $.map(allData, function(item) {

                    return new Data1(item);
                });

                self.List1(test);

            }
        });

 };

 this.loadSecondService = function (id) {

        var input =
            {
                Id: id

            };

        $.ajax({
            url: "../RestService/someService",
            type: "PUT",
            contentType: 'application/json',
            processData: false,
            data: JSON.stringify(input),
            error: function(XMLHttpRequest, textStatus, errorThrown) {

                alert(errorThrown);
            },

            success: function(allData) {
                var test = $.map(allData, function(item) {

                    return new Data2(item);
                });

                self.List2(test);

            }
        });

};

Issue is that it goes inside  $.when and prints   console.log("now we are will start logic); and then calls the services. How can i call services first and then perform some logic when services are hit successfully?
Let me know if its not clear enough.

A: You need your methods to return deferred objects.
this.loadSecondService = function (id) {
    var input = {
        Id: id
    };
    return $.ajax({
        ...
    });

next, you need to handle the logic around receiving the data within .done()
$.when(callFirstService(), callSecondService()).done(function (firstService,secondService) {
    console.log("Both services are done");
})


text:
Q: Downloading a Private Access file from Google drive via API Is it possible to download a private access file from Google drive via api?
The reason I want this is to prevent people from sharing the download link because I want to provide files for paid customer only.
If its not what are my option to provide file download only for paid customers and preventing them from sharing those download links with others?

A: You may want to set scopes for your users to restrict the level of access. See Download Files.

Downloading the file requires the user to have at least read access. Additionally, your app must be authorized with a scope that allows reading of file content. For example, an app using the drive.readonly.metadata scope would not be authorized to download the file contents. Users with edit permission may restrict downloading by read-only users by setting the viewersCanCopyContent field to true.

You may also want to look at Files especially the viewersCanCopyContent.

viewersCanCopyContent
boolean
Whether users with only reader or commenter permission can copy the file's content. This affects copy, download, and print operations.


text:
Q: How to calculate start radius, end radius and angle for clothoid segments? I have a following construction:
Clothoid -- Circle Arc -- Clothoid -- Clothoid
which should form a smooth G2-continuous curve.
Clothoids are parameterized with clothoid parameter $A$ and length $L$. For the circle, its radius and arc length are given.
I should get the clothoids parameterized through start radius, end radius and angle. Can this be done?
I tried with usual formulas that can be found on wikipedia and on this site. For the first clothoid i took a big start radius i.e. $R=\infty$ and went on from there, taking the last end radius as the next starting one and so on. This didn't work as I thought.

A: You didn't say how exactly it didn't work, but it should have worked.
You are given $Clo_1(A_1,L_1)$, $Arc(R,L)$, $Clo_2(A_2,L_2)$, $Clo_3(A_3,L_3)$.
You want  $Clo_1(R_{11},R_{12},\Delta\Theta_1)$, $Clo_2(R_{21},R_{22},\Delta\Theta_2)$, $Clo_3(R_{31},R_{32},\Delta\Theta_3)$ where $R_{12} = R = R_{21}$, $Clo_1$ goes from $s_{11}$ to $s_{12}$, $L_1 = s_{12} - s_{11}$, $R_{Clo_1}(s_{11}) = R_{11}$, $R_{Clo_1}(s_{12}) = R_{12}$, etc.
Then we must have $\{ R_{11}s_{11} = (A_1)^2 = R_{12}s_{12} = Rs_{12}, L_1 = s_{12} - s_{11} \}$ (and similarly for $\__2$ and $\__3$).
The above system of two equations is trivially solvable, for each of the clothoids, giving us their edge radii $R_{ij}$, the $s_{ij}$ values, and hence their edge $\Theta$s, and hence their $\Delta\Theta$s:
$$ \Theta = s^2/2A^2 $$
$$ \Theta_1 = s_1^2/(2R_1s_1) = s_1/(2R_1)$$
$$\Theta_2 = s_2/(2R_2)$$
$$ \Delta\Theta_1 = \Theta_2 - \Theta_1$$
Your error seems to be that
you started from setting $R_{11}=\infty$. Instead, the arc's radius determines the rest.


text:
Q: Generating a list of tuple in a specific order So here is my problem. I have 2 frequencies, and I generate a list of tuple of frequencies nearby.
f1 = 20
f2 = 50
f = [(a, b) for a in range(f1-3, f1+4) for b in range(f2-3, f2+4)]

Output:
[(17, 47), (17, 48), (17, 49), (17, 50), (17, 51), (17, 52), (17, 53), (18, 47), (18, 48), (18, 49), (18, 50), (18, 51), (18, 52), (18, 53), (19, 47), (19, 48), (19, 49), (19, 50), (19, 51), (19, 52), (19, 53), (20, 47), (20, 48), (20, 49), (20, 50), (20, 51), (20, 52), (20, 53), (21, 47), (21, 48), (21, 49), (21, 50), (21, 51), (21, 52), (21, 53), (22, 47), (22, 48), (22, 49), (22, 50), (22, 51), (22, 52), (22, 53), (23, 47), (23, 48), (23, 49), (23, 50), (23, 51), (23, 52), (23, 53)]

Now I order it by it's distance to f1 and f2. With the example above:
[(20, 50), (19, 50), (20, 49), (21, 50), (20, 51), (21, 51), ..., (15, 45), (25, 55)]

A lambda function can do the job:
sorted(f, key=lambda x: abs(f1-x[0]) + abs(f2-x[1]))

Output:
[(20, 50), (19, 50), (20, 49), (20, 51), (21, 50), (18, 50), (19, 49), (19, 51), ...]

Issue 1: How to modify the lambda function in order to get the values (21,51) before (18, 50) (a distance of 1 on each frequency is better than a distance of 2 on one frequency)?
Issue 2: Sorting a list is quite time-consuming (here it's only a 49 elts list, but in reality, it can have thousands of tuples). Is there a way to directly generate the final list and thus to skip the sorting step?
EDIT: Clarification for issue 2
I want to directly generate the final list. The only solution I could think of is a bit heavy:
Instead of:
f = [(a, b) for a in range(f1-3, f1+4) for b in range(f2-3, f2+4)]

Use:
f = [(f1, f2)] + [(a, b) for a in range(f1, f1+2) for b in range(f2, f2+2)] + [(a, b) for a in range(f1, f1-2, -1) for b in range(f2, f2-2, -1)] + ... Distance of 2 + Distance of 3 + so on

Aside from the heavy line, I create duplicates which can be eliminated by list(set(f)) but then I lose the time gained by not sorting...
Thanks.

A: Regarding Issue 1 you could use geometric distance measure:
import math
...
sorted(f, key=lambda x: math.sqrt(pow(f1-x[0],2) + pow(f2-x[1],2)))

A: One option is to use standard deviation of distances as a second key. This has the benefit of combining your 2 pieces of sorting logic in one algorithm.
import numpy as np

f1 = 20
f2 = 50
f = [(a, b) for a in range(f1-3, f1+4) for b in range(f2-3, f2+4)]

res = sorted(f, key=lambda x: [abs(f1-x[0]) + abs(f2-x[1]),
                               np.std([abs(f1-x[0]), abs(f2-x[1])])])

# [(20, 50), (19, 50), (20, 49), (20, 51), (21, 50), (19, 49), (19, 51), (21, 49), (21, 51), (18, 50), (20, 48), (20, 52), (22, 50), (18, 49), (18, 51), (19, 48), (19, 52), (21, 48), (21, 52), (22, 49), (22, 51), (17, 50), (20, 47), (20, 53), (23, 50), (18, 48), (18, 52), (22, 48), (22, 52), (17, 49), (17, 51), (19, 47), (19, 53), (21, 47), (21, 53), (23, 49), (23, 51), (17, 48), (17, 52), (18, 47), (18, 53), (22, 47), (22, 53), (23, 48), (23, 52), (17, 47), (17, 53), (23, 47), (23, 53)]

A: For issue 1 I would go with the answer posted by @vlad : use a geometric distance.
Assuming this suits you, you can look at issue 2 in geometric terms : let f1 be the X axis and f2 the Y axis. Frequency tuples at an equal distance of (f1, f2) will be on a circle around (f1, f2). It doesn't matter where the center point (f1, f2) lies, the closest points will always be at the same (x, y) offset from (f1, f2). This means you can calculate once and for all the ordering of these offsets, then add them to whatever (f1, f2) you are interested in.
# do this once, and keep this variable around
offsets = [(a, b) for a in range(-3, +4) for b in range(-3, +4)]
offsets.sort(key=lambda x: x[0] ** 2 + x[1] ** 2)

# for any f1, f2 get the closest tuples
closest = [(f1 + o[0], f2 + o[1]) for o in offsets]


text:
Q: Wordpress show old data on front end I have used Jobify Theme with WP job manager. I am importing job listing directly in mysql from xml(from jobadder Api) using my custom code. Job listing is proper in admin panel, but wrong(old data) on front job listing page. There are some points that I checked that:-
wrong data only when select full listing without any search data.
If There is any keyword, category or location in search its showing new(correct) data.
Its showing new data on job detail page also.
Admin panel job list also show new data.
when I click edit for any one job and update, even nothing change, its start showing new data everywhere.
get_posts() return old data as i check in code.
I have tried this link
https://wordpress.org/support/topic/wp-job-manager-listing-jobs-with-wp-all-import
Please can anyone help me.

A: <?php
    $args = array( 'posts_per_page' => 20, 'offset'=> 1, 'post_type' => 'job_listing','post_status'      => 'publish' );
    $jobs = get_posts( $args );
?>

A: Thanks for support.
My problem is solved. I update last inserted post(job_listing) using wordpress code. My code is

<?php
           $type='job_listing';
         $id = $wpdb->get_var( $wpdb->prepare(
                "
                    SELECT ID
                    FROM wp_posts
                    WHERE post_type = %s
                    ORDER BY ID DESC limit 0,1
                ",
                $type
            ) );
     $my_post = get_post($id);
     wp_update_post( $my_post );
?>


text:
Q: nsExec::ExecToStack fails when running NSIS script tring to run DOS command Please note that I am attempting to create a data file as part of my installation script.  Here is what I am using:
  # Create config.dat based on user`s previous selection
  nsExec::ExecToStack '"$SYSDIR\cmd.exe" @echo ServerPort = 2003 > $INSTDIR\config.dat'
  Pop $0 # return value/error/timeout
  Pop $1 # printed text, up to ${NSIS_MAX_STRLEN}
  DetailPrint '$SYSDIR\cmd.exe "@echo ServerPort = 2003 > $INSTDIR\config.dat" printed: $1'
  DetailPrint ""
  DetailPrint "       Return value: $0"
  DetailPrint ""

When I run the script, the above returns a 0, so I think it should have worked but when I check the installation directory I see that no config.dat file has been created.
Also, I have tried this command,
nsExec::ExecToStack '@echo ServerPort = 2003 > $INSTDIR\config.dat'

But when I use it the display prints:
Return value: error

Here are websites I have looked at but it is still not clear to me how to get nsExec working.

*

*https://nsis.sourceforge.io/NsExec_plug-in

*https://nsis.sourceforge.io/Docs/Chapter4.html

*Does nsExec::ExecToStack is waiting the process to finish?(NSIS)

*Exec vs ExecWait vs ExecShell vs nsExec::Exec vs nsExec::ExecToLog vs nsExec::ExecToStack vs ExecDos vs ExeCmd

*Execute Command-Line Command from NSIS
Does anyone have any suggestions?  TIA.

A: Please note that I have found the issue.  I thought nsExec mainly worked with the command line, but you have to start with cmd:
nsExec::ExecToStack  'cmd /c "@echo ServerPort = 2003 > config.dat"'

For details please see:
Execute Command-Line Command from NSIS


text:
Q: SQLAlchemy filter Many-to-One - uselist=False I have following tables:
Articles

id
data_art_no
old_price
new_price
date

3353
132252
NULL
24.5
2021-05-07

2886
132252
31
24.5
2021-05-06

2406
132252
NULL
31
2021-05-05

1921
132252
NULL
31
2021-05-04

Data

art_no
multiplier

132252
NULL

And this are my models:
class Data(Base):
    __tablename__ = "data"

    art_no = Column(BigInteger, primary_key=True, index=True)
    multiplier = Column(Float)

    article = relationship("Article", uselist=False, order_by="Article.date.desc()")

class Article(Base):
    __tablename__ = "articles"

    id = Column(BigInteger, primary_key=True, index=True)
    data_art_no = Column(BigInteger, ForeignKey("data.art_no"))
    old_price = Column(Float)
    new_price = Column(Float)
    date = Column(Date)

This should map several articles to a data "element", but in the data element the related article should always be the latest one by id.
However, when I query following:
db.query(models.Data).join(models.Article).filter(models.Article.date == Date(2021, 5, 6)).all()

I expect to get following return:
{ "art_no": 132252, "multiplier": null, "article": { "old_price": 31, "new_price": 24.5 } }

However, but I still get the latest article as returned article value:
{ "art_no": 132252, "multiplier": null, "article": { "old_price": null, "new_price": 24.5 } }

Why don't I get the article I want to get loaded into my Data element? Why is not the Article #2886 being the Article which is loaded into the Data row?


text:
Q: JavaFX tableview to be populated from CSV I'm new to JavaFX and I'm just trying to populate a tableview defined in FXML from a CSV text file. My code is as follows:
package student;

import java.net.URL;
import java.util.*;
import javafx.fxml.*;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;

public class StudInfoController implements Initializable {

    @FXML
    private Tab profile;
    @FXML
    private Label namelbl;
    @FXML
    private Label clslbl;
    @FXML
    private Label divlbl;
    @FXML
    private Label rnolbl;
    @FXML
    private Label maillbl;
    @FXML
    private Label moblbl;
    @FXML
    private Label altlbl;
    @FXML
    private Tab exams;
    @FXML
    private Tab result;
    @FXML
    private TableView<Exam> ExamTable;
    @FXML
    private TableView<Result> ResultTable;
    @FXML
    private TableColumn<Exam, String> eSub;
    @FXML
    private TableColumn<Exam, String> eDate;
    @FXML
    private TableColumn<Exam, String> eDur;
    @FXML
    private TableColumn<Exam, String> eMarks;
    @FXML
    private TableColumn<Result, String> rSub;
    @FXML
    private TableColumn<Result, String> rDate;
    @FXML
    private TableColumn<Result, String> rTT;
    @FXML
    private TableColumn<Result, String> rTE;
    @FXML
    private TableColumn<Result, String> rMarks;

    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
        eSub.setCellValueFactory(new PropertyValueFactory<>("eSub"));

        eDate.setCellValueFactory(new PropertyValueFactory<>("eDate"));
        eDur.setCellValueFactory(new PropertyValueFactory<>("eDur"));
        eMarks.setCellValueFactory(new PropertyValueFactory<>("eMarks"));
        rSub.setCellValueFactory(new PropertyValueFactory<>("rSub"));
        rDate.setCellValueFactory(new PropertyValueFactory<>("rDate"));
        rTT.setCellValueFactory(new PropertyValueFactory<>("rTT"));
        rTE.setCellValueFactory(new PropertyValueFactory<>("rTE"));
        rMarks.setCellValueFactory(new PropertyValueFactory<>("rMarks"));
        ExamTable.getItems().setAll(InsertExam());
        ResultTable.getItems().setAll(InsertResult());
    }

    private List<Exam> InsertExam() {
        try {
            FileRead fr = new FileRead();
            String[] l = fr.examRead();
            String[] items;
            int i = 0;
            Exam r = new Exam();
            List<Exam> row = new ArrayList<>();
            for (i = 0; i < l.length; i++) {

                items = l[i].split(",");
                r.setESub(items[0]);
                r.setEDate(items[1]);
                r.setEDur(items[2]);
                r.setEMarks(items[3]);
                row.add(r);
            }

            return row;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private List<Result> InsertResult() {
        try {
            FileRead fr = new FileRead();
            String[] l = fr.resultRead();
            String[] items;
            Result r = new Result();
            List<Result> row = new ArrayList<>();
            for (int i = 0; i < l.length; i++) {

                items = l[i].split(",");
                r.setRSub(items[0]);
                r.setRDate(items[1]);
                r.setRTT(items[2]);
                r.setRTE(items[3]);
                r.setRMarks(items[4]);
                row.add(r);
            }

            return row;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    class Exam {

        private String eSub;

        private String eDate;

        private String eDur;

        private String eMarks;

        public Exam() {
        }

        public String getESub() {
            return eSub;
        }

        public void setESub(String eSub) {
            this.eSub = eSub;
        }

        public String getEDate() {
            return eDate;
        }

        public void setEDate(String eDate) {
            this.eDate = eDate;
        }

        public String getEDur() {
            return eDur;
        }

        public void setEDur(String eDur) {
            this.eDur = eDur;
        }

        public String getEMarks() {
            return eMarks;
        }

        public void setEMarks(String eMarks) {
            this.eMarks = eMarks;
        }
    }

    class Result {

        private String rSub;

        private String rDate;

        private String rTT;

        private String rTE;

        private String rMarks;

        public String getRSub() {
            return rSub;
        }

        public void setRSub(String rSub) {
            this.rSub = rSub;
        }

        public String getRDate() {
            return rDate;
        }

        public void setRDate(String rDate) {
            this.rDate = rDate;
        }

        public String getRTT() {
            return rTT;
        }

        public void setRTT(String rTT) {
            this.rTT = rTT;
        }

        public String getRTE() {
            return rTE;
        }

        public void setRTE(String rTE) {
            this.rTE = rTE;
        }

        public String getRMarks() {
            return rMarks;
        }

        public void setRMarks(String rMarks) {
            this.rMarks = rMarks;
        }

        public Result() {
        }
    }

}

The FXML code is as follows:
<TableView fx:id="ResultTable" prefHeight="345.0" prefWidth="697.0">
    <columns>
        <TableColumn fx:id="rSub" editable="false" prefWidth="297.0"
                     text="SUBJECT"/>
        <TableColumn fx:id="rDate" editable="false" prefWidth="97.0"
                     text="DATE"   />
        <TableColumn fx:id="rTT" editable="false" prefWidth="123.0"
                     text="TOTAL   TIME"/>
        <TableColumn fx:id="rTE" editable="false" prefWidth="116.0"
                     text="TIME    ELAPSED" />
        <TableColumn fx:id="rMarks" editable="false" prefWidth="63.0"
                     text="MARKS" />
    </columns>
</TableView>
<TableView fx:id="ExamTable" prefHeight="344.0" prefWidth="697.0">
    <columns>
        <TableColumn fx:id="eSub" editable="false" prefWidth="414.0"
                     text="SUBJECT" />
        <TableColumn fx:id="eDate" editable="false" prefWidth="148.0"
                     text="DATE" />
        <TableColumn fx:id="eDur" editable="false" prefWidth="79.0"
                     text="DURATION" />
        <TableColumn fx:id="eMarks" editable="false" prefWidth="55.0"
                     text="MARKS" />
    </columns>
</TableView>

The following exception is being thrown:
Executing C:\Users\ANIL\Documents\NetBeansProjects\Student\dist\run775021387\Student.jar using platform C:\Program Files\Java\jdk1.8.0_111\jre/bin/java
java.lang.RuntimeException: java.lang.IllegalAccessException: Class sun.reflect.misc.Trampoline can not access a member of class student.StudInfoController$Result with modifiers "public"
    at com.sun.javafx.property.PropertyReference.get(PropertyReference.java:177)
    at javafx.scene.control.cell.PropertyValueFactory.getCellDataReflectively(PropertyValueFactory.java:147)
    at javafx.scene.control.cell.PropertyValueFactory.call(PropertyValueFactory.java:119)
    at javafx.scene.control.cell.PropertyValueFactory.call(PropertyValueFactory.java:98)
    at javafx.scene.control.TableColumn.getCellObservableValue(TableColumn.java:578)
    at javafx.scene.control.TableColumn.getCellObservableValue(TableColumn.java:563)
    at javafx.scene.control.TableCell.updateItem(TableCell.java:644)
    at javafx.scene.control.TableCell.indexChanged(TableCell.java:468)
    at javafx.scene.control.IndexedCell.updateIndex(IndexedCell.java:116)
    at com.sun.javafx.scene.control.skin.TableRowSkinBase.updateCells(TableRowSkinBase.java:533)
    at com.sun.javafx.scene.control.skin.TableRowSkinBase.init(TableRowSkinBase.java:147)
    at com.sun.javafx.scene.control.skin.TableRowSkin.<init>(TableRowSkin.java:64)
    at javafx.scene.control.TableRow.createDefaultSkin(TableRow.java:212)
    at javafx.scene.control.Control.impl_processCSS(Control.java:872)
    at javafx.scene.Node.processCSS(Node.java:9058)
    at javafx.scene.Node.applyCss(Node.java:9155)
    at com.sun.javafx.scene.control.skin.VirtualFlow.setCellIndex(VirtualFlow.java:1964)
    at com.sun.javafx.scene.control.skin.VirtualFlow.getCell(VirtualFlow.java:1797)
    at com.sun.javafx.scene.control.skin.VirtualFlow.getCellLength(VirtualFlow.java:1879)
    at com.sun.javafx.scene.control.skin.VirtualFlow.computeViewportOffset(VirtualFlow.java:2528)
    at com.sun.javafx.scene.control.skin.VirtualFlow.layoutChildren(VirtualFlow.java:1189)
    at javafx.scene.Parent.layout(Parent.java:1087)
    at javafx.scene.Parent.layout(Parent.java:1093)
    at javafx.scene.Parent.layout(Parent.java:1093)
    at javafx.scene.Parent.layout(Parent.java:1093)
    at javafx.scene.Parent.layout(Parent.java:1093)
    at javafx.scene.Parent.layout(Parent.java:1093)
    at javafx.scene.Scene.doLayoutPass(Scene.java:552)
    at javafx.scene.Scene.preferredSize(Scene.java:1646)
    at javafx.scene.Scene.impl_preferredSize(Scene.java:1720)
    at javafx.stage.Window$9.invalidated(Window.java:846)
    at javafx.beans.property.BooleanPropertyBase.markInvalid(BooleanPropertyBase.java:109)
    at javafx.beans.property.BooleanPropertyBase.set(BooleanPropertyBase.java:144)
    at javafx.stage.Window.setShowing(Window.java:922)
    at javafx.stage.Window.show(Window.java:937)
    at javafx.stage.Stage.show(Stage.java:259)
    at student.StudentFXMLController.OKBtnAction(StudentFXMLController.java:65)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Node.fireEvent(Node.java:8413)
    at javafx.scene.control.Button.fire(Button.java:185)
    at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:380)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:294)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:416)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:415)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalAccessException: Class sun.reflect.misc.Trampoline can not access a member of class student.StudInfoController$Result with modifiers "public"
    at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:102)
    at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(AccessibleObject.java:296)
    at java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:288)
    at java.lang.reflect.Method.invoke(Method.java:491)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
    at com.sun.javafx.property.PropertyReference.get(PropertyReference.java:175)
    ... 94 more
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.IllegalAccessException: Class sun.reflect.misc.Trampoline can not access a member of class student.StudInfoController$Result with modifiers "public"
    at com.sun.javafx.property.PropertyReference.get(PropertyReference.java:177)
    at javafx.scene.control.cell.PropertyValueFactory.getCellDataReflectively(PropertyValueFactory.java:147)
    at javafx.scene.control.cell.PropertyValueFactory.call(PropertyValueFactory.java:119)
    at javafx.scene.control.cell.PropertyValueFactory.call(PropertyValueFactory.java:98)
    at javafx.scene.control.TableColumn.getCellObservableValue(TableColumn.java:578)
    at javafx.scene.control.TableColumn.getCellObservableValue(TableColumn.java:563)
    at javafx.scene.control.TableCell.updateItem(TableCell.java:644)
    at javafx.scene.control.TableCell.indexChanged(TableCell.java:468)
    at javafx.scene.control.IndexedCell.updateIndex(IndexedCell.java:116)
    at com.sun.javafx.scene.control.skin.TableRowSkinBase.updateCells(TableRowSkinBase.java:533)
    at com.sun.javafx.scene.control.skin.TableRowSkinBase.init(TableRowSkinBase.java:147)
    at com.sun.javafx.scene.control.skin.TableRowSkin.<init>(TableRowSkin.java:64)
    at javafx.scene.control.TableRow.createDefaultSkin(TableRow.java:212)
    at javafx.scene.control.Control.impl_processCSS(Control.java:872)
    at javafx.scene.Parent.impl_processCSS(Parent.java:1280)
    at javafx.scene.Parent.impl_processCSS(Parent.java:1280)
    at javafx.scene.Parent.impl_processCSS(Parent.java:1280)
    at javafx.scene.control.Control.impl_processCSS(Control.java:868)
    at javafx.scene.Parent.impl_processCSS(Parent.java:1280)
    at javafx.scene.Parent.impl_processCSS(Parent.java:1280)
    at javafx.scene.Parent.impl_processCSS(Parent.java:1280)
    at javafx.scene.control.Control.impl_processCSS(Control.java:868)
    at javafx.scene.Node.processCSS(Node.java:9058)
    at javafx.scene.Node.processCSS(Node.java:9051)
    at javafx.scene.Scene.doCSSPass(Scene.java:545)
    at javafx.scene.Scene.access$3600(Scene.java:159)
    at javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2392)
    at com.sun.javafx.tk.Toolkit.lambda$runPulse$30(Toolkit.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.Toolkit.runPulse(Toolkit.java:354)
    at com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:381)
    at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:510)
    at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:490)
    at com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$404(QuantumToolkit.java:319)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalAccessException: Class sun.reflect.misc.Trampoline can not access a member of class student.StudInfoController$Result with modifiers "public"
    at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:102)
    at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(AccessibleObject.java:296)
    at java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:288)
    at java.lang.reflect.Method.invoke(Method.java:491)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
    at com.sun.javafx.property.PropertyReference.get(PropertyReference.java:175)
    ... 37 more

A: Well the issue was with the class declaration. the class has to be public. And the issue is resolved. thanks for the help


text:
Q: Pressure at the outlet of a pipe I am revising for a fluid dynamics exams and I am struggling with the following question:
Consider a pipe that consists of a horizontal segment with a varying cross-sectional
area that is aligned along the $x-axis$ and a downward segment of height, $h$, that
is parallel to the $z -axis$. The two segments are joined together by a smooth bend.
Water flowing smoothly within the pipe experiences a gravitational force $g = −gk$
where $g$ is the gravitational acceleration and $\mathbf k$ is the unit normal pointing in
the positive $z -direction$, with $z = 0$ along the horizontal segment of the pipe. The
cross-sectional area at the inlet is given by $A_1$ while the area at the outlet is $A_2$ .
If
the pressure at the inlet of the horizontal section is at atmospheric pressure given
by $p_a$ , and the inlet velocity is $V_1$ , find the pressure at the outlet of the pipe.
I think I'm supposed to use Bernoulli's equations but I'm not sure which form and I struggle to interpret it so an explanation would be great.
Thanks!

A: Very simply , Let velocity at end be $v_2$ and Area of cross section be $A_2$
$$v_1\times A_1=v_2 \times A_2\tag{mass conservation in fluids}$$
Now, we know that $P+h\rho g+ \frac{1}{2}\rho v^2$ is constant,
$$P_a+h\rho g +\frac{1}{2}\rho v_1^2=P+\frac{1}{2}\rho\frac {(v_1A_1)^2}{(A_2)^2}$$
Therefore, answer is :
$$P_a+h\rho g + \frac{1}{2}\rho \frac{v_1^2(A_2^2-A_1^2)}{A_2^2}$$


text:
Q: How to alternate train op's in tensorflow? I am implementing an alternating training scheme. The graph contains two training ops. The training should alternate between these.
This is relevant for research like this or this
Below is a small example. But it seems to update both the ops at every step. How can I explicitly alternate between these?
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
# Import data
mnist = input_data.read_data_sets('/tmp/tensorflow/mnist/input_data', one_hot=True)

# Create the model
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]), name='weights')
b = tf.Variable(tf.zeros([10]), name='biases')
y = tf.matmul(x, W) + b

# Define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
global_step = tf.Variable(0, trainable=False)

tvars1 = [b]
train_step1 = tf.train.GradientDescentOptimizer(0.5).apply_gradients(zip(tf.gradients(cross_entropy, tvars1), tvars1), global_step)
tvars2 = [W]
train_step2 = tf.train.GradientDescentOptimizer(0.5).apply_gradients(zip(tf.gradients(cross_entropy, tvars2), tvars2), global_step)
train_step = tf.cond(tf.equal(tf.mod(global_step,2), 0), true_fn= lambda:train_step1, false_fn=lambda : train_step2)

sess = tf.InteractiveSession()
tf.global_variables_initializer().run()

# Train
for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
    if i % 100 == 0:
        print(sess.run([cross_entropy, global_step], feed_dict={x: mnist.test.images,
                                         y_: mnist.test.labels}))

This results in
[2.0890141, 2]
[0.38277805, 202]
[0.33943111, 402]
[0.32314575, 602]
[0.3113254, 802]
[0.3006627, 1002]
[0.2965056, 1202]
[0.29858461, 1402]
[0.29135355, 1602]
[0.29006076, 1802]

The global step iterates to 1802, so both train ops are executed each time  train_step is called. (This also happens when the always-false condition is tf.equal(global_step,-1) for example.)
My question is how to alternate between executing train_step1 and train_step2?

A: I think the simplest way is just
for i in range(1000):
  batch_xs, batch_ys = mnist.train.next_batch(100)
  if i % 2 == 0:
    sess.run(train_step1, feed_dict={x: batch_xs, y_: batch_ys})
  else:
    sess.run(train_step2, feed_dict={x: batch_xs, y_: batch_ys})

But if it's necessary to make a switch via tensorflow conditional flow, do it this way:
optimizer = tf.train.GradientDescentOptimizer(0.5)
train_step = tf.cond(tf.equal(tf.mod(global_step, 2), 0),
                     true_fn=lambda: optimizer.apply_gradients(zip(tf.gradients(cross_entropy, tvars1), tvars1), global_step),
                     false_fn=lambda: optimizer.apply_gradients(zip(tf.gradients(cross_entropy, tvars2), tvars2), global_step))


text:
Q: Madri killed by Apocalypse himself There's a comic in the Age of Apocalypse called The chosen, where a Madri goes into the computer of Apocalypse in order to know if the Madri are chosen or forgotten. It says at the second page of the issue: "But only one of the Madri would dare access his most classified data".
I knew that the Madri were replicas of Madrox, is there something special about this gossip Madri, or just someone put there without reason?

A: As far as we can tell, no. By using the phrase "But only one of the Madri would dare access his most classified data", I believe that it was meant to convey that Apocalypse viewed this particular Madri as either un-loyal or insane to his cause, which was punishable by death, regardless of who you were.


text:
Q: send input file with special characters (such as accents) to the web server I´m working with asp classic and using IIS like web server.
i have to send files (using input files) from the html web page.
The problem is when i have special caracteres in the files´ name.
For example: when the file´s name is "Distribución de tareas para desarrollo.docx" and the name reaches the server like "Distribución de tareas para desarrollo.docx"
Here is my html head code.

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

I try to work with the charset in the html code and the asp code but it´s does´t work.
Now add these lines as suggested by the user @Daniel Nordh.
`
 <%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
 <% Response.CodePage = 65001
    Response.CharSet = "UTF-8"
 %>

`
But, the result is the same.
Well it seems that I am facing the issue badly.
I know that when sending input file from the browser, the data arrives with binary files.
Once I separate the header I see that the file reaches the server it does as follows.
-----------------------------7e33a72830078c Content-Disposition: form-data; name="doc"; filename="Distribución de tareas para desarrollo.docx" Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document PK
And reading the name is the same way I get.
But if I write the following code on the same page asp.
response.write "
panificación
"

When requesting the page is displayed.
panificación.
What I am thinking about is that I have the problem because it is input files that are sent as binary files.
HTML form to send the files.

<form  method="post" action="files.asp" target="_blank"
  enctype="multipart/form-data">

              <input accept=".doc,.docx" type="file" name="archivo">
                    doc (opcional)

 </form>

Here the code that processes the files received.
The variables and comments are in Spanish.
<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%
    Response.CodePage = 65001
    Response.CharSet = "UTF-8"
%>
<%

dim v_recordset
dim v_arreglo_archivos
dim v_archivo
dim v_bytes
dim v_posicion_limite
dim v_datos_binarios
dim v_longitud_binaria
dim v_agregar_lvc
dim v_datos_completos
dim v_inicio_archivo
dim v_final_archivo
dim v_cadena_delimitadora
dim v_datos_archivo
dim v_inicio_nombre
dim v_fin_nombre
dim v_cadena_nombre_archivo
dim v_pos_temp
dim v_pos_previa
dim v_nombre_archivo
dim v_content_type
dim v_inicio_datos
dim v_fin_datos
dim v_longitud_datos
dim v_file_object
dim v_creador_archivos
dim v_datos_enviados
dim v_cantidad_archivos_subidos
dim v_bandera_archivo_lleno

set v_recordset=CreateObject("ADODB.Recordset")

on error resume next

v_agregar_lvc=201
v_cantidad_archivos_subidos=0

v_bytes=request.totalBytes
v_datos_binarios=request.BinaryRead(v_bytes)
v_longitud_binaria=LenB(v_datos_binarios)

if v_longitud_binaria>0 then
    v_recordset.Fields.Append "mi_binario",v_agregar_lvc,v_longitud_binaria
    v_recordset.Open
    v_recordset.AddNew
    v_recordset("mi_binario").AppendChunk v_datos_binarios
    v_recordset.Update
    v_datos_completos=v_recordset("mi_binario")
end if

v_encabezado=request.ServerVariables("HTTP_CONTENT_TYPE")
v_posicion_limite=instr(1,v_encabezado,"boundary=") + 8

 v_cadena_delimitadora= right(v_encabezado,len(v_encabezado)- v_posicion_limite)

v_cadena_delimitadora="--" &v_cadena_delimitadora

v_inicio_archivo=instr(1,v_datos_completos,v_cadena_delimitadora)

 v_final_archivo=instr(v_inicio_archivo+1,v_datos_completos,
 v_cadena_delimitadora)-1

  do while v_final_archivo>0

    v_datos_archivo=mid(v_datos_completos,v_inicio_archivo,v_final_archivo -
    v_inicio_archivo)

    v_inicio_nombre=instr(1,v_datos_archivo,"filename=")+10
    v_fin_nombre=instr(v_inicio_nombre,v_datos_archivo,chr(34))

    v_datos_completos=replace(v_datos_completos,v_datos_archivo,"")

    if v_inicio_nombre=v_fin_nombre then

        v_bandera_archivo_lleno=false

        do while not v_bandera_archivo_lleno

           v_inicio_archivo=instr(1,v_datos_completos,
                            v_cadena_delimitadora)
           v_final_archivo=instr(v_inicio_archivo+1,v_datos_completos,
                            v_cadena_delimitadora)-1

           v_datos_archivo=mid(v_datos_completos,v_inicio_archivo,
                           v_final_archivo - v_inicio_archivo)

           v_inicio_nombre=instr(1,v_datos_archivo,"filename=")+10
           v_fin_nombre=instr(v_inicio_nombre,v_datos_archivo,chr(34))

            if v_inicio_nombre<>v_fin_nombre then
                v_bandera_archivo_lleno=true
            end if

            v_datos_completos=replace(v_datos_completos,v_datos_archivo,"")

        loop

    end if

     if v_inicio_nombre<>v_fin_nombre then

     v_cadena_nombre_archivo=mid(v_datos_archivo,v_inicio_nombre,
                                v_fin_nombre - v_inicio_nombre)
     v_pos_temp=instr(1,v_cadena_nombre_archivo,"\")

        do while v_pos_temp>0

            v_pos_previa=v_pos_temp
            v_pos_temp=instr(v_pos_previa+1,v_cadena_nombre_archivo,"\")
        loop

        v_nombre_archivo=right(v_cadena_nombre_archivo,
                        len(v_cadena_nombre_archivo) - v_pos_temp)

        v_content_type=instr(1,v_datos_archivo,"Content-type:")

        if v_content_type>0 then
        v_inicio_datos=instr(v_content_type,v_datos_archivo,chr(13)&chr(10))
                        + 4
        else
            v_inicio_datos=v_fin_nombre
        end if

        v_fin_datos=len(v_datos_archivo)

        v_longitud_datos=v_fin_datos - v_inicio_datos
        v_datos_enviados=mid(v_datos_archivo,v_inicio_datos,v_fin_datos)

    end if

    v_inicio_archivo=instr(1,v_datos_completos,v_cadena_delimitadora)
    v_final_archivo=instr(v_inicio_archivo+1,v_datos_completos,
                    v_cadena_delimitadora)-1

loop

okay. Once the content is obtained it is saved on the server. But that is something else that is not causing me trouble.

A: Make sure you save your files as UTF-8 as well. Try adding this to the very top of the page(s) you're working with. Encoding and ASP Classic can be a nightmare from my own experience.
<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%
response.codepage = 65001
response.charset = "utf-8"
%>


text:
Q: i am having issue using query function of google sheets I am trying to query an XLSX file with the following statement =query($A$2:$E$34, "select E WHERE C = '1' AND A = 'Jun-21'"), in that case, C being a country number and A being the month and year and I am not able to get a value, I receive N/A saying that it has been completed with an empty result, even though there is a number matching criteria on the dataset

A: try:
=INDEX(QUERY(TO_TEXT(A2:E34), "select Col5 where Col3 = '1' and Col1 = 'Jun-21'"))