text:
Q: Getting image in URL What's trouble, I can't download image without saving on Hard Disk Drive by
try {
         sentenceLabel= new JLabel(new ImageIcon(ImageIO.read(new URL("http://www.google.ru/intl/en_com/images/logo_plain.png"))));
    } catch (MalformedURLException ex) {
        // TODO Auto-generated catch block
        ex.printStackTrace();
    } catch (IOException ex) {
        // "http://img.yandex.net/i/wiz"+imgType.trim()+".png"
        ex.printStackTrace();
    }

What's wrong? Sorry for noob question

A: You can use this code to download an Image:
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;

public class ImageDownloader
{
    public static void main(String[] args )
    {
        BufferedImage image =null;
        try{

            URL url =new URL("http://developerfeed.com/sites/default/files
                             /have_a_question.png");
            // read the url
           image = ImageIO.read(url);

            for png
            ImageIO.write(image, "png",new File("/tmp/have_a_question.png"));

            // for jpg
            ImageIO.write(image, "jpg",new File("/tmp/have_a_question.jpg"));

        }catch(IOException e){
            e.printStackTrace();
        }
    }}

A: Your code is completely fine. This shows me the image in the content pane.
    JFrame frame = new JFrame();
    frame.setTitle("Polygons");
    frame.setSize(550, 550);
    Container contentPane = frame.getContentPane();
    try {
     JLabel sentenceLabel= new JLabel(new ImageIcon(
                  ImageIO.read(new URL(
                     "http://www.google.ru/intl/en_com/images/logo_plain.png"))));
     contentPane.add(sentenceLabel);
    } catch (MalformedURLException ex) {
        // TODO Auto-generated catch block
        ex.printStackTrace();
    } catch (IOException ex) {
        // "http://img.yandex.net/i/wiz"+imgType.trim()+".png"
        ex.printStackTrace();
    }
    frame.show();


text:
Q: Is this still a factory method? What if I don't need a special factory class and I want a concrete client to instantiate right parts. The client needs to call Hello() from that part. Everywhere else the focus is on making the factory method a method of a special creator class. But here it is right away in a client. Is this still a factory method pattern and is it even correct to use it as shown below?
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            AClient c1 = new ClientUsingPart1();
            c1.Foo();
            AClient c2 = new ClientUsingPart2();
            c2.Foo();
            Console.ReadKey();
        }
    }

    abstract class AClient
    {
        public AClient() { this.ipart = Create(); }

        public void Foo() { ipart.Hello(); }
        // many other methods
        // ...
        public abstract IPart Create();  // factory method
        IPart ipart;
    }

    class ClientUsingPart1 : AClient
    {
        public override IPart Create() { return new Part1(); }
    }

    class ClientUsingPart2 : AClient
    {
        public override IPart Create() { return new Part2(); }
    }

    interface IPart
    {
        void Hello();
    }

    class Part1 : IPart
    {
        public void Hello() { Console.WriteLine("hello from part1"); }
    }
    class Part2 : IPart
    {
        public void Hello() { Console.WriteLine("hello from part2"); }
    }

}

A: Depending on exactly what you need to achieve you should probably use some for of dependency injection with an IoC container of your choice; with StructureMap, Autofac, Unit, Ninject, Castle Windsor all very popular. Once you IoC container has built the concrete classes it should support a syntax like this
foreach (var client in Container.Resolve<IEnumerable<AClient>>())
{
    client.Create();
}

You can read more about how to achieve this with StructureMap here: Does an abstract class work with StructureMap like an interface does?

A: According to this:
Differences between Abstract Factory Pattern and Factory Method
It seems the code I posted in the original post shows a valid use of the factory method pattern. The key is - factory method is just a method of the class - which also may be the sole client of the created objects.
Or in another way: factory method does not need to be public and provide the created objects to the outside world. In my example the Create() method should be protected.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What kind of C++ code would generate this x86 assembly instruction? I have been "reverse engineering" some of my own libraries to learn more about compiler optimizations. I have seen one of my simplest class constructors (a 4-D vector) get compiled to the following:
fldz                                                        ; push +0.0 to FPU stack
mov     eax, ecx                                            ; set eax to this (ecx)
mov     dword ptr [eax], offset data_??_7vector_t@data@@6B@ ; what is this doing?
fst     dword ptr [eax+4]                                   ; assign this->first
fst     dword ptr [eax+8]                                   ; assign this->second
fst     dword ptr [eax+0Ch]                                 ; assign this->third
fstp    dword ptr [eax+10h]                                 ; assign this->fourth, pop FPU stack
retn                                                        ; return this (eax)

On the third line, I have no clue what this is doing. I originally thought it might be some kind of optimization that is referencing some hard coded block of constant data.
In order to determine what it might be, I loaded the DLL into a container process and then attached a debugger and viewed the data at the location of data??_7vector_t@data@@6B@, but it was just db offset unk??_7vector_t@data2@@6B@. I followed that second label and there was a region of data which didn't correspond to anything I recognized in my project, even after converting the first 8 bytes into a double.
The compiler I'm using is MSVC++ with Visual Studio 2013 with full optimization without any advanced instruction sets (SSE, etc is turned off).
What C++ code would generate the instruction in question?

A: The line in question is assigning a vtable pointer to the object being constructed.

A: Looks to me like it is applying a constructor to the uninitialized storage at ECX.
The steps of that would insert a vtable pointer in its first slot, and zero the 4d vector you say your application uses.

A: Not sure where the data_ prefix comes from, but the ? is the standard marker of decorated (mangled) names and you can use the undname tool to decipher them:
>undname ??_7vector_t@data@@6B@
Microsoft (R) C++ Name Undecorator
Copyright (C) Microsoft Corporation. All rights reserved.

Undecoration of :- "??_7vector_t@data@@6B@"
is :- "const data::vector_t::`vftable'"

So yes, it's just initializing the vtable pointer.


text:
Q: Does this method of level shifting work? I'm curious if this method of level shifting works fine or not; or it suits the design I manage to do.
I want to extend the cable length of both an I2C, and an I2C-like, low clocked communication sensor(SHTxx sensors). I've seen many articles and answers on this website, which most of them conclude on using PCA9xxx I2C bus buffers. the reason that I'm not considering them, is that the added cost and very low availability on my local stores, is not reasonable according to the required robustness.
These are the conditions:

*

*A maximum of 8 meters of a cheap 4*AWG28 shielded cable for the sensor[s]. the supply voltage of the sensor is sent via one of the AWG28 threads. the exact specifications (e.g. the capacitance) are not available.

*Communication speed is not concerned. any clock value would be fine.

*It doesn't need to obtain an international standard. it just needs to be trusted to over 70% successful transactions.

I saw some simple, mosfet-based level shifters, which are used in cheap modules available. It is said they are fine for up to 2MHz of SPI, and 400KHz I2C communications. however, I don't know if they can be used like this or not.
Here is my Idea (based on above application note, and the aforementioned modules)  to shift the voltage of the cable to a higher value (e.g. 9V or 12V considering the mosfets maximum tolerant drain-source voltage) and translate the signal levels to this value; perhaps the same way RS232 buffers do it, so the signal is more robust to noise. the sensors supply would be drawn from the same 12V supply line that the cable signals are pulled up to.

simulate this circuit – Schematic created using CircuitLab
The shield will be connected to the GND of the MCU side only.

*

*Does this design, do what I expect, according to the conditions mentioned above? or it's just a foolish try. (I'm not sure because despite the apparent simplicity, I have not seen any design like that)

*If it works, is there any considerations I should make to make it better?

thank you for your time, and the knowledge.

A: No, this setup does not improve noise immunity at all; in fact, quite the opposite. Unlike RS232 drivers and receivers, this kind of level shifter has no voltage or current gain.
Consider what happens when a device at either end wants to pull a line low. It must now do that through two transistors and a long wire, and it must sink the current of all three pullups. The low level at the other end of the wire can only be degraded by all of this, and that's before you consider any noise coupled into the cable.
Running the middle of the connection at a higher voltage has no benefit at all. The devices at either end only see the voltage of their local pullup.


text:
Q: Lim trace of inverse positive definite matrices We have a symmetric positive definite matrix $A \in \Bbb R^{m \times m}$. How to calculate the following?
$$ \lim_{n \to \infty} \mbox{tr} \big( (\underbrace{A\cdot A\cdots A}_n)^{-1} - (\underbrace{A\cdot A\cdots A}_n + \underbrace{A\cdot A\cdots A}_{2n})^{-1} \big)$$
The main issue for me is how to transform the right-hand part of the expression containing inverse of the sum of matrices. The rest is more or less clear.

A: Note that as $A$ is symmetric positive definite we can use the spectral theorem to write
$$
A = \sum_i \lambda_i P_i
$$
where $\lambda_i > 0$ are the eigenvalues (up to multiplicity) and $\{P_i\}_i$ form a set of orthogonal projectors onto the corresponding eigenspaces. Note that $\mathrm{Tr}[P_i] = d_i$ where $d_i$ is the dimension of the eigenspace.
From this form you can see that for example
$$
A^{k} = \sum_i \lambda_i^k P_i\,
$$
for any $k \in \mathbb{Z}$. And furthermore
$$
(A^n + A^{2n})^{-1} = \sum_i \frac{1}{\lambda_i^n + \lambda_i^{2n}} P_i
$$
Putting everything together we arrive at
$$
\mathrm{Tr}[A^{-n} - (A^n + A^{2n})^{-1}] = \sum_i d_i \left(\frac{1}{\lambda_i^n} - \frac{1}{\lambda_i^n + \lambda_i^{2n}}\right) = \sum_i d_i \frac{\lambda_i^{2n}}{\lambda_i^{2n} + \lambda_i^{3n}}
$$
Looking at each term in the sum individually they split into two cases. If $\lambda_i > 1$ then the term tends to $0$ otherwise if $0 < \lambda_i \leq 1$ then the term tends to $d_i$. Overall we find that
$$
\lim_{n \to \infty} \mathrm{Tr}[A^{-n} - (A^n + A^{2n})^{-1}] = \sum_{i : \lambda_i \leq 1} d_i
$$
i.e., the total dimension of the eigenspaces corresponding to eigenvalues of $A$ that are no larger than $1$.


text:
Q: I need to create an interface in c# and a method to load a list of the interface Having the two class/inteface below:
[Schema("dbo")]
[Alias("Team")]
public class Team : IHasId<int>
{
    [Alias("TeamId"), AutoIncrement]
    public int Id { get; set;}

    [Required]
    public string TeamName { get; set;}

    [Required]
    public DateTime CreatedOn { get; set;}

    [Required]
    public int DivisionId { get; set; }

    [Required]
    public bool IsActive { get; set; }
}

public interface ITotal
{
    DateTime Date { get; set; }
    Team Team { get; set; }
    Account Account { get; set; }
    double Total { get; set; }
}

public class Total: ITotal
{
    public DateTime Date {get; set;}
    public Team Team {get; set;}
    public Account {get; set;}
    public double Total {get; set;}
}

I am trying to create a default method to return a sum of total by Team id, I am not very familiar using interfaces, so I am not sure if what I did was the best solution, also should I use something like ITotalCollection instead of List ?
public class QueryTotalCollection: List<Total>
{
    public List<Total> GetTotalByTeam()
    {

        // todo: I need to return here the same object. However,
        // grouping by Team and the Sum of .Total (in this case the
        // property "Account" will return null as I am grouping by Team.
        // for instance: select Date, Team, null as Account, sum(Total)
        //               group by Date, Team
        // return this.GroupBy(x => x.Team.Id)...

    }
}

The method above is not working, how can I do this? I want to return a
sum of ITotal.Total grouped by Team.Id

A: There is basic misuse of interfaces and what you think it does. First of all if you want to create a class that does return a sum of total, then do just that. You need no interfaces for that.
But if you have multiple classes (at least two) that will implement ITotal interface, then I would recommend use helper method, as it is what you need (you need helper method right?). Info about extending class. Sample code:
public static class TeamSelectHeleper
{
    public static double GetTotalByTeam(this List<ITotal> myList)
    {
        // TODO Sum wont work this way - fix it
        //return myList.GroupBy(x => x.Team.Id).Sum(s => s.Total);

        // If you need just a sum, then just sum it.
        // but if you need group results,
        // then you can just return on number when there is a list
        return myList.Sum(s => s.Total);
    }
}

You can then apply this method to any list containing ITotal.
And group by doesn't work the way you think it does. Use stack answer or MSDN

A: You need to properly implement that ITotal interface with one of your classes which will include all the declared methods of that interface. Something like this :
public class QueryTotalCollection: ITotal
{
    public double Total()
    {
        //your actual method body code.
    }
}

Also, you might want to read some basic stuff about Interfaces and how they are used and implemented. That should help you through this.
Hope this helps.


text:
Q: What are the advantages and disadvantages of higher order neuron activation functions? I've been reading about different types of neurons that the traditional linear one. One example I came across is the Sigma-Pi neuron, where the activation function includes higher order terms, such as

What are the advantages and disadvantages of using neurons like that? Why do we tend not to use them in favour of the traditional wX(+b)?


text:
Q: How Encoder passes Attention Matrix to Decoder in Tranformers 'Attention is all you need'? I was reading the renowned paper 'Attention is all you need'. Though I am clear with most of the major concepts, got buggy with a few points

*

*How Encoder pass the attention matrix calculated using the input to Decoder? Like what I understood is it only passes the Key & Value matrix to the decoder

*From where do we get shifted output for the decoder while testing?

*As it is able to output just one token at a time, is this transformer run for multiple iterations to generate output sequence. If yes, then, how to know when to stop?

*Are weights trained in Multi-Head Attention in the decoder as it already gets Q,K & V from encoder & masked multi-head attention

Any help is appreciated

A: *

*The Encoder passes the 'Attention' matrix calculated. This attention matrix is considered as the 'Key' & 'Value' matrix for the Decoder Multi-Head Attention module

*Why do we need shifted output for testing? It is not required as when testing, we need to predict from token one for which 'BOS' (Beginning Of Sequence) token is considered as past token & hence automatically left-shifted

*Yes, we need to iterate over & over predicting one token at a time. If the predicted token is 'EOS' (End Of Sequence), we stop

*This isn't clear but looks like the Decoder's multi-head attention isn't trained


text:
Q: Videogular2 Get video duration return NaN I'm in an angular project  with Videogular2 and I've got a problem with retrieving video duration.
The Vgapi have a duration property.
duration [read-only] :number
Returns the duration in seconds.
When I'm using it. It returns Nan.
When i'm looking at source :
 * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming.
     */
    readonly duration: number;
    /**

The video is in mp4 format. the duration file meta tag is filled (1:00 minute)
I will try ogg and webm form to see if it's make the job.
Someone maybe have experience on videogular2 ?
Thanks to all :)

A: onPlayerReady(api:VgAPI)
{
  this.api = api;
  this.api.getDefaultMedia().subscriptions.ended.subscribe(
    ($event) => { this.router.navigate(['home'])

  });
  this.api.getDefaultMedia().subscriptions.loadedMetadata.subscribe(
    ($event) => {
  this.duration=this.api.duration;
  console.log("API  "+this.api.duration);
  });
}

when Metadata are loaded you can get duration.


text:
Q: Querying a HP printer using RESTSharp over USB I need to query a HP printer using REST(Sharp) over USB.  Windows application.
My C# applications works great using an IP address.  Now I want to do the same thing but use a USB port.  I don't know how to format the connection string
This is the code that connects nicely to the printer over the network:
var client = new RestClient(@"http://204.145.155.155");

var request = new RestRequest(@"/OemsiMediapath/OemsiMediapathDyn.xml",       Method.GET);

IRestResponse response = client.Execute(request);

I am stuck with what string to supply the the RestClient constructor for a usb port.   For example, the printer is on USB002.  I have unsuccessfully tried:
var client = new RestClient(@"http://USB002");

and
 var client = new RestClient(@"USB002");

I have googled a lot on this and discovered that I am one of the VERY FEW people using REST in this sort of applications :(


text:
Q: Divide JSON into equal smaller parts using php I have a JSON containing lets say 14 elements.
How can I divide it in smaller JSONs of lets say 2 or 3 elements each.

A: Do not know what your exact json is, but this will serve as an example:
<?php

$jsonExample = '["a","b","c","d","e","f","g","h","i"]' ;
$arrResult = json_decode($jsonExample,true);
$output = array_chunk($arrResult,3);
var_dump($output);

?>

demo:http://codepad.org/aYBg19DB

A: I would recommend using json_decode() and array_chunk().
http://php.net/manual/en/function.array-chunk.php
http://php.net/manual/en/function.json-decode.php


text:
Q: To which part of the sentence the "which"s refer?
Thus, in a last analysis it can be seen that the chief cause of the
  downfall of the Sasanians was the material and spiritual bankruptcy
  of the ruling class, which especially became apparent after the
  bad government of Khusrau Parviz, and which must account for the
  crumbling of so great a power before the attacks of a hungry
  people newly arrived on the scene... Read more

*

*Do both "which"s refer to "the chief cause of the downfall of the Sasanians"?

*Does "a power" mean "the Sasanians" in here? If not, what does it mean?

A: *

*Both  instances of "which" refer to "the material and spiritual bankrupcy of the ruling class".

*Yes, the "power" here means the Sasanians.


text:
Q: What is the meaning of "N" in this sentence? The meaning of "jackrabbit" in Oxford dictionary is:
a large N American hare(=an animal like a large rabbit) with very long ears.
My question is what is the meaning of "N" in this sentence?


text:
Q: How do I UnSnap a Snapped app? I registered to the OnSizeChanged event of my Page, like that:
private void OnSizeChanged(object sender, SizeChangedEventArgs e)
{
    ApplicationViewState myViewState = ApplicationView.Value;
    if (myViewState == ApplicationViewState.Snapped)
    {
         Windows.UI.ViewManagement.ApplicationView.TryUnsnap();
    }
}

I'm tyring to set the application-view to Filled/Portrait state when the user trying (manually....) to resize it to snapped view.
but the TryUnsnap method fails and it stays in snapped state...
Help!
Thanks.

A: To understand TryUnsnap() we need to understand the 2 types of Windows 8 events:

*

*Programmatic events
Programmatic events do not require the user to do anything. For example the Loaded event of a Page or the Tick event of a Timer.

*User-initiated events
User-initiated events require the user to do something. For example the Click event of a Button or the Tapped event of a Control.
The important part
Depending on the type of event, only certain Windows 8 APIs can be called. Adding a Secondary Tile, for example. And (as you might have guessed) un-Snapping an app.
That means you can call those APIs all you want from programmatic events but they will never deliver the results you desire. Unsnap in the StateChanged event, and it will fail for this reason. Unsnap in the Button.Click event, and it will succeed for this reason.
The rationale behind this behavior is the user experience. If the app can change it's 'orientation' on the user without the user's interaction then the behavior of the app becomes both confusing and unpredictable. Windows 8 is a pro-user operating system. When you discover developer 'constraints', 99% of the time it is this philosophy behind it.
Let me demonstrate:
If you attached to the StateChanged event, your code would look like this:
this.ApplicationViewStates.CurrentStateChanged += (s, args) =>
{
    System.Diagnostics.Debug.WriteLine("After StateChanged: {0}", this.ApplicationViewStates.CurrentState.Name);
    if (this.ApplicationViewStates.CurrentState == this.Snapped)
    {
        System.Diagnostics.Debug.WriteLine("Before Unsnap: {0}", this.ApplicationViewStates.CurrentState.Name);
        Unsnap();
    }
};

However, the resulting output (in the debugger) would look like this:
After StateChanged: FullScreenLandscape
After StateChanged: Snapped
Before Unsnap: Snapped
After TryUnsnap: Snapped

This is frustrating for a developer who does not understand the difference between programmatic and user-initiated events in Windows 8. The API appears to "not work" when, in fact, it works perfectly. Just not like they want it to.
If you attached to the Click event, your code would look like this:
MyButton.Click += (s, args) =>
{
    System.Diagnostics.Debug.WriteLine("After Button.Click: {0}", this.ApplicationViewStates.CurrentState.Name);
    if (this.ApplicationViewStates.CurrentState == this.Snapped)
    {
        System.Diagnostics.Debug.WriteLine("Before Unsnap: {0}", this.ApplicationViewStates.CurrentState.Name);
        Unsnap();
    }
};

Then, the resulting output would look like this:
After Button.Click: Snapped
Before Unsnap: Snapped
After TryUnsnap: Snapped
After StateChanged: FullScreenLandscape

This gets you what you want, but it brings up an important point. See how After TryUnsnap the state REMAINS "Snapped"? The transition of a Visual State from one to another is not a synchronous event. Calling for a change takes an unpredictable amount of time. It's probably done with a dispatch post, but I would have to check to be sure.
Having said all that, the state does change. And, after the change the CurrentStateChanged event is raised and you can handle the new Snapped state. By the way, it does not matter if there is another snapped app, this works either way.

The MSDN docs say it only works when it is in the foreground. This is pretty stupid since user interaction can't occur on a background app, and background apps have their threads suspended anyway. But, to be fair to MSDN, this API does not work when your app is in the background - whatever that's worth.

I hope this helps clear it up.
And now to your question:
You want to go from Snapped to Portrait? Of course in Portrait, Snapped is not possible so this is not a possibility for you to code. You want to go from Snapped to Filled as soon as the app is snapped. The event raised from the Snapped action is a programmatic event. As a result, you have to lure the user into doing something in your UI first. So, no you can't do what you are asking. You can't Unsnap() until the user interacts with your app somehow (like a button click event).
Oh, and here's the Unsnap() method if you wanted to reference all my code. I am not doing anything special, but you might be interested:
void Unsnap()
{
    if (Windows.UI.ViewManagement.ApplicationView.TryUnsnap())
        // successfully unsnapped
        System.Diagnostics.Debug.WriteLine("After TryUnsnap: {0}", this.ApplicationViewStates.CurrentState.Name);
    else
        // un-successfully unsnapped
        System.Diagnostics.Debug.WriteLine("After TryUnsnap: {0}", this.ApplicationViewStates.CurrentState.Name);
}

Have a great day and best of luck!

A:             var CurrentSnappedState = ApplicationView.Value;
            if (CurrentSnappedState == ApplicationViewState.Snapped && !ApplicationView.TryUnsnap())
            {
                return;
            }

Should do the trick. Remember that you can still snap the page, but when you try to do anything in the snapped page you will be redirected to the fullview.


text:
Q: NullPointerException in the Netbeans tutorial for Java EE I try to follow the Netbeans e-commerce tutorial to familiarize myself with Netbeans. I use Netbeans 7.0, the tutorial is recommended for Netbeans 6.8-6.9. Usually the adaptations are quite easy (the displayed elements are in a different order, or there are more fields).
The tutorial states in the third chapter: "Make sure that the 'Enable Contexts and Dependency Injection' option is deselected."
For chapter 7, I adapt it according to what it says in chapter 7, especially adding the following code in ControllerServlet:
@EJB
private CategoryFacade categoryFacade;

public void init() throws ServletException {

    // store category list in servlet context
    getServletContext().setAttribute("categories", categoryFacade.findAll()); // line 37
}

I try to run it when they say to run it, and I receive a NullPointerException on line 37. Line 37 is the actual code in the init method written here above. The exception occurs on the server side, so I guess that at some point, the people who wrote the tutorial changed their mind and activated CDI. I tried to add a dummy beans.xml to fix the issue, without success.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
      http://java.sun.com/xml/ns/javaee
      http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>

After this, I downloaded the code provided and redid the work from their "breakpoint" (file AffableBean_snapshot3.zip), I got the same NullPointerException. I also took the version of the project as it should be after this part of the tutorial (AffableBean_snapshot4.zip) and it still fails at the exact same point.
So, what am I doing wrong? Should I really use Netbeans 6.9 instead of 7.0? The only notable difference is the filename of some xml file that are sun-* in Netbeans 6.9 and glassfish-* in Netbeans 7.0.


text:
Q: Multivariable Calc Proof Suppose that $F(x,y,z)=0$ is an equation so that any variable can be solved in terms of the other two. Show that
$\displaystyle \frac{\partial x}{\partial y}\cdot\frac{\partial y}{\partial z}\cdot \frac{\partial z}{\partial x}= -1.$
I understand what the question means and I am able to see how it works for a linear equation but assuming I can't set up a general linear equation (I don't think it would be sufficient enough) how would I do this proof.

A: Let me write it as $$x_yy_zz_x$$
$$=x_y\dfrac{z_x}{z_y}$$ and by implicit differantation remember that $y_x=\dfrac{-G_x}{G_y}$ so we have $x_y(-y_x)=-1$.
Note: we regard $z=G(x,y)$


text:
Q: Do variables of interlocked functions have to declared as volatile in native C++ Is there a difference between :
    __declspec(align(8)) long long variable1; //assume shared among threads
    InterlockedIncrement64(&variable1);

And this:
    __declspec(align(8)) long long volatile variable2;//assume shared among threads
    InterlockedIncrement64(&variable2);

My guess would be that they operate exactly the same in this scenario. I think the only difference would be that if variable1 is accessed without an interlocked function it is not guaranteed to be a current value while variable2is guaranteed to be a current value. Example:
long long x = variable1; //Not guaranteed to be the most recent value when accessed
long long y = variable2; //Guaranteed to be the most recent value when accessed

Am I correct in my assumptions?
Note: I am using /volatile:ms compiler option in visual studio


text:
Q: How do I query just one level of a table-per-type mapping? I'm using Entity Framework 4.1's code first approach to map a class hierarchy to a series of tables.
I have the following classes defined:
[Table("FooBases")]
public class FooBase
{
    public int Id { get; set; }
    public string Name { get; set; }
}

[Table("Foo1s")]
public class Foo1 : FooBase
{
    public string Details { get; set; }
}

[Table("Foo2s")]
public class Foo2 : FooBase
{
    public string Description { get; set; }
}

So this will create three tables, where the common properties (Id and Name) are stored in a FooBase table.
In one particular case I am only interested in a list of names of any kind of FooBase object. I don't care whether it's a Foo1 or a Foo2. I spin up a new data context and run a query like this:
var names = ctx.Set<FooBase>().Select(f => f.Name);

Now, I don't need the overhead of querying the Foo1s and Foo2s tables. I expect the query to just be a simple SELECT Name FROM FooBases. Instead, I get this:
SELECT
[Extent1].[Name] AS [Name]
FROM  [dbo].[FooBases] AS [Extent1]
LEFT OUTER JOIN  (SELECT
    [Extent2].[Id] AS [Id]
    FROM [dbo].[Foo1s] AS [Extent2]
UNION ALL
    SELECT
    [Extent3].[Id] AS [Id]
    FROM [dbo].[Foo2s] AS [Extent3]) AS [UnionAll1] ON [Extent1].[Id] = [UnionAll1].[Id]

Is there a way to tell Entity Framework that I don't care about the other tables; that I just want data from the top level of the class hierarchy so there's no need to query anything other than the top level table?

A: This is well known issue with Table-per-type inheritance mapping. It should be addressed in upcoming EFv4.2 which should improve the query generation for TPT inheritance. At the moment there is no way to improve it.


text:
Q: UICollectionView crash on cell insertion I have a UICollectionView with a footer supplementary view. The way the collectionView works, it is possible to push the supplementary view offscreen when a new cell is inserted. The cells can have different horizontal sizing.
If two large cells are inserted and the supplementary view is pushed off of the screen, inserting a small cell between the two larger cells causes a crash.
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException',
reason: 'the view returned from -collectionView:viewForSupplementaryElementOfKind:
atIndexPath (UICollectionElementKindCell,<NSIndexPath: 0xc00000000000000e>
{length = 1, path = 0}) was not retrieved by calling
-dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath: or is nil ((null))'

I have determined that the crash occurs because the supplementary view is nil. It is nil because in
 - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
   viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath

I check to see what kind of element has been handed to the method. When the app crashes, the kind is UICollectionElementKindCell, for which I have no valid response.
So, my question is twofold :
1) Why is viewForSupplementaryElementOfKind being called with a kind that is not associated with my supplementary view? I expect that the UICollectionView should only try to get supplementary view information from this method.
2) How can this crash be avoided?

A: It is unclear why, but this crash was resolved by overriding the method
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds

and returning true as well as removing the call to invalidateLayout that was in the insertion methods.


text:
Q: How to auto-remove orphaned rows in TypeORM? I have a one-to-many relation in TypeORM and I would like to delete rows from the many side of the relationship rather than unlinking them by setting their foreign key to null (the default behavior), leaving them orphaned.  How can this be done? I saw a PR for this feature but it was rejected. Is there a workaround or some other way to do this? Here's a simplified version of my code to give some context.
@Entity()
@TableInheritance({ column: { name: 'type', type: 'text' } })
export default class Geolocation {
  @PrimaryGeneratedColumn()
  id!: number;

  @IsGeoJSONPoint
  @Column('geography')
  point!: Point;
}

@ChildEntity('offer')
export default class OfferGeolocation extends Geolocation {
  @ManyToOne(type => Offer, offer => offer.geolocations, { onDelete: 'CASCADE' })
  offer!: Offer;
}

@ChildEntity('business')
export default class BusinessGeolocation extends Geolocation {
  @ManyToOne(type => Business, business => business.geolocations, { onDelete: 'CASCADE' })
  business!: Business;
}

@Entity()
export default class Business {
  @PrimaryGeneratedColumn()
  id!: number;

  // I would like to remove orphaned business geolocations
  @OneToMany(type => BusinessGeolocation, businessGeolocation => businessGeolocation.business, { cascade: true })
  geolocations!: BusinessGeolocation[];
}

@Entity()
export default class Offer {
  @PrimaryGeneratedColumn()
  id!: number;

  // I would like to remove orphaned offer geolocations as well
  @OneToMany(type => OfferGeolocation, offerGeolocation => offerGeolocation.offer, { cascade: true })
  geolocations!: OfferGeolocation[];
}

A: There was another PR which was merged on Jan 12th 2021, which fixes this.
This feature is available since TypeORM version 0.2.30:

0.2.30 (2021-01-12)
Features

*

*relations: Orphaned row action (#7105) (efc2837)

You should be able to achieve what you want by:
@ChildEntity('business')
export default class BusinessGeolocation extends Geolocation {
  @ManyToOne(
    type => Business, business => business.geolocations, {
      onDelete: 'CASCADE',
      orphanedRowAction: "delete" // NEW
    })
  business!: Business;
}


text:
Q: Cannot submit form with a hidden input in Cakephp so I have a form that contains a hidden input.
 <?= $this->Form->create(null, [ 'class' => '', 'templates' => 'Inspinia.form_basic']) ?>
    <?php
        echo $this->Form->control('name');
        echo $this->Form->control('description', ['type' => 'text']);
        echo $this->Form->control('chart_type', [ 'options' => $this->App->availableCharts() ] );
        echo $this->Form->control('frequency', [ 'options' => ['monthly' => 'Monthly','quarterly'=>'Quarterly','snapshot' =>'Snapshot','monthly/quarterly' => 'Monthly/Quarterly'] ] );
        echo $this->Form->control('public', [ 'options' => ['1' => 'Public','0' => 'Private'] ] );
        // $this->Form->unlockField('deleted');
        echo $this->Form->hidden('deleted',['value' => 0]);
    ?>
<?= $this->Form->button(__('Save'), ['class' => 'btn btn-sm btn-primary pull-right m-t-n-xs']) ?>
<?= $this->Form->end() ?>

Whenever I try to submit the form, it throws me this error
Missing field 'deleted' in POST data

I know I can bypass this by just doing
$this->Form->unlockField('deleted');

but I don't want to bypass the security component in Cakephp, so is there any other way I can get CakePhp to allow me to submit this hidden field?
this is my controller nothing too much but here just in case you guys are wondering
public function test() {

    if ($this->request->is('post')) {
        debug($this->request->data);
    }
}

A: It should like below
<?php
  echo $this->Form->input('nameoffield',array('type'=>'hidden'));
?>

or passing a hidden value
<?php
$hidden_value = 0;
echo $this->Form->input('nameoffield',array('type'=>'hidden','value' => $hidden_value));
?>


text:
Q: Get Taxonomy term url from sharepoint rest api So I was wondering if there is a way to get a term url from the sharepoint rest api by selecting the right property...
I have this right now but I have now idea what to select :
_api/v2.1/termStore/groups/{groupId}/sets/{setId}/terms/{termId}?$select=*,{URL?}
What should I replace URL with ?


text:
Q: Unable to instantiate an object using parameterized Constructor in java This is the class I want to Instantiate:
public class GoogleSheetsAPI {

String spreadsheetId;
Sheets service;
String credentialsFile;

public void GoogleSheetsAPI() {
}

public void GoogleSheetsAPI(String spreadsheetId, String credentialsFile) throws Exception {
    this.spreadsheetId = spreadsheetId;
    this.credentialsFile = credentialsFile;
    service = getSheetsService();
}

}
This is how I am creating an object of class GoogleSheetsAPI
GoogleSheetsAPI googleSheetsAPI = new GoogleSheetsAPI(spreadsheetId, credentiialsFile);

A: The constructor must not have void, it should be:
public GoogleSheetsAPI(String spreadsheetId, String credentialsFile) throws Exception {
    this.spreadsheetId = spreadsheetId;
    this.credentialsFile = credentialsFile;
    service = getSheetsService();
}

A: the constructor does not have any return type... because is a special method, if you define own constructor then not define empty constructor because jvm provide default...

A: Class.newInstance invokes the no-arg constructor
Class<?> cl = Class.forName("javax.swing.JLabel");
Constructor<?> cons = cl.getConstructor(String.class);

Object o = cons.newInstance("JLabel");
to invoke a different constructor, you need to use the reflection package (java.lang.reflect).


text:
Q: What is the cause/use/reason for the blocks that show up in high compression videos? Be patient since I haven't worked with compression algorithms much so this may be obvious to some of you. Something I've always noticed when some streaming video starts to lag. I only realized I was curious when looking over this question:
Twitter image encoding challenge
I'm not talking about the pixels themselves but rather the grid like layout that results from the compression. What sort of algorithm or technique is this indicative of? What can you tell me about it?

A: Take a look at this Wikipedia article on MPEG-2.  To quote a part of it:

Briefly, the raw frame is divided into 8 pixel by 8 pixel blocks. The data in each block is transformed by a discrete cosine transform. The result is an 8 by 8 matrix of coefficients. The transform converts spatial variations into frequency variations, but it does not change the information in the block; the original block can be recreated exactly by applying the inverse cosine transform.

In other words, the grid-like structure you see is a direct effect of this DCT being applied to the 8x8 blocks of pixels.

A: The rationale for blocks is linked to the location/frequency trade off. The image is divided into blocks before the compression in the spectral domain (DCT) so that the artefacts due to the compression are more localized. In standard JPEG, the blocks are of constant size on the whole picture. For more recent formats like JPEG2000, the blocks are adapted to the picture, using wavelets. I am not familiar with video formats details, but the rationale is the same.
This is the same phenomenon for audio coding (mp3): instead of computing the spectrum on the whole audio file, you split the file into some sections of a few samples (a few hundred generally for 44.1 kHz signals). And similarly, if there is corruption of the compressed data (network, corrupted file), you will hear noises which are due to missing windows.

A: It's called Macroblocking.


text:
Q: Pass a list of struct pointers from Python to c++ using Swig I am trying to call a c++ function from Python using using a wrapper created using Swig.
func.cpp
#include "func.h"
void funcCall(Query* queries[]) {
    queries[0]->key = 4;
    queries[0]->val = 5;
}

func.h
#ifndef TESTPROJECT_FUNC_H
#define TESTPROJECT_FUNC_H

#include "string.h"

#endif //TESTPROJECT_FUNC_H

struct Query {
    int key;
    int val;
};

extern "C" void funcCall(Query* queries[]);

func_w.i
%module func_w
%include <cstring.i>

%{
#include "func.h"
%}

%typemap(in) Query*[] {
    $1 = NULL;
    if (PyList_Check($input)) {
        const size_t size = PyList_Size($input);
        Query* ans[size+1];
        $1 = &ans[0];
        for (int i = 0; i < size; ++i) {
            Query *argp = 0 ;
            const int res = SWIG_ConvertPtr(PyList_GetItem($input, i), (void**)&argp, $*1_descriptor, 0);
            if (!SWIG_IsOK(res)) {
                SWIG_exception_fail(SWIG_ArgError(res), "in method '" "$symname" "', argument " "$argnum"" of type '" "$1_type""'");
            }
            $1[i] = argp;
        }
        $1[size] = NULL;
    }
    else {
        // Raise exception
        SWIG_exception_fail(SWIG_TypeError, "Expected list in $symname");
    }
}

%include "func.h"

test.py
import func_w

if __name__ == '__main__':
    query = func_w.Query()
    func_w.funcCall([query])
    print(">>> ", query.key, query.val)

The above code throws Segmentation fault.
I am not sure about the type map but without it it gives "TypeError: in method 'funcCall', argument 1 of type 'Query *[]'" error.
Referred to How to pass list of structs to C in SWIG/Python for interface file


text:
Q: How to calculate grand total of total values using FetchXML I am new to FetchXML but enjoying the experience thus far. I have a report I am working on and I would like to get a grand total. The grand total is meant to be a sum of the results of row totals.

I want to calculate the value of XXXX.
I used this to calculate the value of the row totals:
=((Len(ReportItems!Textbox4.Value)) + (Len(ReportItems!Textbox6.Value)) + (Len(ReportItems!Textbox8.Value)) + (Len(ReportItems!Textbox10.Value)))/3

and I attempted to use this to calculate the grand total but I keep getting an error stating I can aggregate functions can only be used on report items contained in page headers and footers
=SUM(ReportItems!Textbox22)

I would appreciate any assistance. Thank you

A: It's pretty simple.
You want to calculate total of column Total no of products.
First make values of your that column as Number i.e data type of that column as number May it be float integer or so on.
Once you do that when you right click on any cell under Total no of products,
You will get option as Total i.e Ssrs by default gives you option for Total if your column data type is number.  Here is the example link.
Look for adding Total to report
https://learn.microsoft.com/en-us/sql/reporting-services/lesson-6-adding-grouping-and-totals-reporting-services?view=sql-server-2017

A: Yon can use aggregate in FetchXML as in SQL. this is the syntax:
string sumFetch= @"
  <fetch distinct='false' mapping='logical' aggregate='true'>
   <entity name='opportunity'>
     <attribute name='estimatedvalue' alias='estimatedvalue_sum' aggregate='sum' />
   </entity>
 </fetch>";

var sumResult = _serviceProxy.RetrieveMultiple(new FetchExpression(sumFetch));

foreach (var c in sumResult.Entities)
{
   decimal sum = ((Money)((AliasedValue)c["sumResult"]).Value).Value;
   System.Console.WriteLine("Sum of estimated value of all opportunities: " + sum );
}

Here is the documantion:
https://learn.microsoft.com/en-us/powerapps/developer/common-data-service/use-fetchxml-aggregation


text:
Q: Start Task Manager from VBScript on windows 8.1 On windows versions prior to windows 8 my installer was using VB Script similar to this one to start task manager:
' StartProcessLocal.vbs
' Free example VBScript to start a process (not interactive)
' Author Guy Thomas
' Version 1.8 - December 2010
' -------------------------------------------------------'
Option Explicit
Dim objWMIService, objProcess, objCalc
Dim strShell, objProgram, strComputer, strExe

strComputer = "."
strExe = "Taskmgr.exe"
' Connect to WMI
set objWMIService = getobject("winmgmts://"_
& strComputer & "/root/cimv2")

' Obtain the Win32_Process class of object.
Set objProcess = objWMIService.Get("Win32_Process")
Set objProgram = objProcess.Methods_( _
"Create").InParameters.SpawnInstance_
objProgram.CommandLine = strExe

'Execute the program now at the command line.
Set strShell = objWMIService.ExecMethod( _
"Win32_Process", "Create", objProgram)

WScript.echo "Created: " & strExe & " on " & strComputer
WSCript.Quit

This doesn't start task manager on windows 8.1.
Taskmgr.exe is in System32 directory and when I double click it it starts fine. It starts fine from command prompt: >Taskmgr.exe
In above example if you change Taskmgr.exe with Calc.exe it starts calculator. Calc.exe is also in System32 folder.
Why above script isn't starting task manager?

A: Did you try to start it by this way ?
Option Explicit
Dim Application
Application = "%windir%\system32\Taskmgr.exe"
Call RunThis(Application)
'*********************************************************************************
Sub RunThis(Application)
    Dim Ws,Result
    Set Ws = CreateObject("WScript.Shell")
    Result = Ws.Run(DblQuote(Application),1,False)
End Sub
'*********************************************************************************
Function DblQuote(Str)
    DblQuote = Chr(34) & Str & Chr(34)
End Function
'*********************************************************************************


text:
Q: Turn JS popup editable when a link is clicked I am basically creating a phonebook web app just as a starting point to my learning in web development. I've created contacts and I have made the contact details displayable as a popup when the particular contact is clicked.
What I would like further is to make each of the fields of the contact details editable! I would probably place an "edit" link at the side of each field and when that is clicked I would like the respective field to become editable.
I've searched, but I couldn't find a solution.
PS: My first question here, so apologies if its not to the point or something.

A: It should be simple. You have to make tree elements for each contact:

*

*contact tex(you already did that)

*edit(button that contains onclick="myFunction()")

*Hidden text field(style="display:none;")

function myFunction(){
document.getElementById("txtB").style.display = "block";
document.getElementById("txt").style.display = "none";
}

function finishedEdit(){
document.getElementById("txtB").style.display = "none";
document.getElementById("txt").style.display = "block";
document.getElementById("txt").innerHTML = document.getElementById("txtB").value;
}
    George Bush<input onchange="finishedEdit()" id="txtB" type="text" value="George Bush" style="display:none;"/><button onclick="myFunction()">Edit</button>

This is not exactly what you want but I can't do much more because I can't see your code.


text:
Q: MYSQL: select records with lowest sort I have this table:
ID | product | image | sort
---------------------------
1  |   1     |  img1 |  1
2  |   1     |  img2 |  1
3  |   1     |  img3 |  2
4  |   2     |  img4 |  1
5  |   2     |  img5 |  2

how can I select the records with lowest sort and lowest id grouping by product?
the result that I would like to get is the following:
ID | product | image | sort
---------------------------
1  |   1     |  img1 |  1
4  |   2     |  img4 |  1

A: Try this:
Select * from table WHERE = (Select MIN(sort) from table) ORDER BY ID ASC group by product


text:
Q: User table for many tables to login I'm trying to build school management system and I'm having trouble designing an optimal database structure. I have Students, Staff and Users tables for login. User table will have login information only (userNumber, password) and Students and Staff will contain personal information. I separated Students and Staff because they contain different personal data. But they both have a userNumber.
users(
id,
userNumber,
password
)

students(
id,
studentNumber,
name,
age
)

staff(
id,
staffNumber,
name,
age,
salary,
dateOfHiring,
staffType
)

Let's say I'm login in with a userNumber 98242, how can let the system know where should I look, in Students table or Staff table?
I would like some recommendations on database structures.

A: just add column userType to users table

A: You could do a few things. You could create a type in the users table and look that up. You could also join the both the tables and then on recieving a record check if the student id or staff id has been returned.
Then your query could be something like
SELECT users.id as user_id, students.id, staff.id FROM users
LEFT JOIN students ON users.id = students.id
LEFT JOIN staff ON users.id = staff.id
WHERE id = 98242

A: Inheritance:
create table persons (
  id,
  name,
  age
);

create table users (
  number,
  password
) inherits (persons);

create table students (
) inherits (users);

create table stuff (
  salary,
  dateOfHiring,
  staffType
) inherits (users);

Schematically, something like this.
Using tableoid system column you could to know the origin of the particular row:
select
  *,
  tableoid::regclass -- Prints the origin table name (users, students, stuff, ...)
from users
where number = 98242;

A: While there are only few separate columns for students and staff members, I would keep it simple:
CREATE TABLE person (
  person_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY
, name      text
, birthday  date  -- never age! bitrots in no time
, student_number int
, staff_number int
, salary       numeric
, hired_at     date
, staff_type   text
, CONSTRAINT one_role_max CHECK (student_number IS NULL
                              OR (staff_number, salary, hired_at, staff_type) IS NULL)
, CONSTRAINT one_role_min CHECK (student_number IS NOT NULL
                              OR (staff_number, salary, hired_at, staff_type) IS NOT NULL)
);

CREATE TABLE users (
  user_number int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY
, person_id   int NOT NULL REFERENCES person
, password    text -- encrypted !
);

This way, one person can have 0-n user accounts - which is the typical reality. You can restrict to a single account per person by adding UNIQUE (person_id) to table users.
The CHECK constraint one_role_max enforces that either student columns or staff columns must stay NULL.
The CHECK constraint one_role_min enforces that at least one of both must have any values.
Adapt what must/can be filled in to your needs. The expressions work excellently for the current design. See:

*

*NOT NULL constraint over a set of columns
While it's strictly "either/or" and the only student column is student_number, this query answers your question:
SELECT CASE WHEN student_number IS NULL THEN 'staff' ELSE 'student' END AS user_role
FROM   person
WHERE  person_id = (SELECT person_id FROM users WHERE user_number = 98242);

Or remove one or both CHECK constraints to allow the same person to be student and staff, or neither. Adapt above query accordingly.
You could use inheritance for this (like Abelisto demonstrates), but I'd rather stay away from it. There once was the idea of an object-relational DBMS. But the community has largely moved on. It works, but with caveats. Partitioning used to be a major use case. But declarative partitioning in Postgres 10 mostly superseded the inheritance-based implementation. There is not too much interest in it any more.
What about all those empty columns? Am I wasting a lot of space there? The opposite is the case. The disk footprint won't get much smaller than this. NULL storage is very cheap. See:

*

*Does not using NULL in PostgreSQL still use a NULL bitmap in the header?


text:
Q: Run sequel of run configurations in Eclipse I work on web applications with eclipse which means each time I modify server side code I have to run maven clean install then start my server again. I have run configurations for these both steps in eclipse but need to wait for the first one to finish before starting the second one.
I have also other cases when I need to run maven clean install on 5 or 6 projects in a given order after having updated all of them.
So my question is: does anybody know how to define sequels of runs and run them in the right order on one click in Eclipse (i'm using Indigo). I didn't found any plugin nor help on my favorite search engine.

A: You can write an Ant-script which wraps the Maven commands (with using Maven Ant Tasks) in the correct order. Then you can create a launch configuration for that Ant script in Eclipse.
Or just write a shell script and create an launch configuration for that in Eclipse.


text:
Q: Display Banners inline and responsive with a given HTML structure I have this HTML:

Now I want to display all banners in 1 line and responsive, so they should resize all the same way on small screens.
This CSS did the job:
.bannerWrapper {
    display: table;
    margin: 5px auto;
}
.bannerCollection {
    display: contents;
}
.bannerCollection .bannerUnit {
    display: table-cell;
    padding: 0 3px;
}
.bannerUnit img {
    max-width: 100%;
}

Here's a JS Fiddle: https://jsfiddle.net/NoGo/8pzsk0m2/
My problem: I cannot use display: contents;, because this seems to cause problems with a Javascript selector.
Any chance to achieve this without changing anything inside div.bannerCollection and without using display: contents;?

A: This design can be accomplished using flexbox. No need for display: contents.
Simply add display: flex to .bannerWrapper and .bannerCollection. Remove display: table-cell from .bannerCollection .bannerUnit
I modified your fiddle here:
https://jsfiddle.net/8pzsk0m2/5/
It's important to note browser support for display: contents is still fairly low, and depending on which browsers you are targeting, it may be wise to avoid its use until it's more widely supported.
https://caniuse.com/#search=display%3A%20contents

A: Try this

.bannerWrapper {
    display: flex;
    margin: 5px auto;
}
.bannerCollection {
    display: flex;
}
.bannerCollection .bannerUnit {
    padding: 0 3px;
}
.bannerUnit img {
    max-width: 100%;
}


text:
Q: recyclerview fill with getter setter is it possible to setCoordinate in viewHolder than getCoordinate in other layout? can i get an example for it? here my viewHolder example:
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class myHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
//views

ImageView mImageIv;
TextView mTitleTv, mDescrTv;

ItemClickListener itemClickListener;

myHolder(@NonNull View itemView) {
    super(itemView);

    this.mImageIv = itemView.findViewById(R.id.Model_ImageIv);
    this.mDescrTv = itemView.findViewById(R.id.Model_DescrTv);
    this.mTitleTv = itemView.findViewById(R.id.Model_TitleTv);
    itemView.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    this.itemClickListener.onItemClick(v, getLayoutPosition());
}
public void setItemClickListener(ItemClickListener ic){
    this.itemClickListener =  ic;
}

}

A: You can add any methods to your ViewHolder.
Then you can use:
recyclerView.findViewHolderForAdapterPosition(position);

or
recyclerView.findContainingItemView(view);
recyclerView.findViewHolderForLayoutPosition(position);
recyclerView.findViewHolderForItemId(id);

to find ViewHolder and call getCoordinate()

A: This operations used to be managed from the adapter that holds the complete set of data. You could update the item you want and then call notifyDataSetChanged() method.


text:
Q: Error creating bean with name : Scope 'request' is not active for the current thread I have integrated SWF 2.2.1,Primefaces 2.2.1,JSF 2,Spring Security 3,Spring 3.1.0M1I and EhCache and AspectJ and Castor.
I have defined beans for castor in my app-config.xml like
<bean id="oXMapper" class="com.abc.xyz.util.OXMapper">
    <property name="unmarshaller" ref="unmarshaller" />
    <property name="marshaller" ref="marshaller" />
    <property name="acordRequest" ref="acordRequest" />
    <property name="acordResponse" ref="acordResponse" />
</bean>

<bean id="unmarshaller" class="org.springframework.oxm.castor.CastorMarshaller">
    <property name="mappingLocation"
        value="classpath:/templates/mapping/ACORD_Response_Mapping.xml" />
</bean>

<bean id="marshaller" class="org.springframework.oxm.castor.CastorMarshaller">
    <property name="mappingLocation"
        value="classpath:/templates/mapping/ACORD_Request_Mapping.xml" />
</bean>

<bean id="acordRequest" class="com.abc.xyz.cate.domain.ACORD">
    <property name="insuranceSvcRq" ref="insuranceSvcRq" />
    <property name="signonRq" ref="CltSearch_signonRq" />
</bean>

I have a search page from where I am building the parameters like
<h:panelGrid>
    <h:selectOneRadio id="#{msg.srchType}" value="#{acordRequest.insuranceSvcRq.com_csc_ClientSearchRq.com_csc_SearchInfo.com_csc_SearchCriteria.com_csc_ClientSearch.com_csc_SearchNameByType}">
        <f:selectItem itemLabel="#{msg.exact}" itemValue="E" id="#{msg.exact}" />
    <f:selectItem itemLabel="#{msg.phonetic}" itemValue="S" id="#{msg.phonetic}" />
    <f:selectItem itemLabel="#{msg.truncated}" itemValue="P" id="#{msg.truncated}" />
        </h:selectOneRadio>
</h:panelGrid>

Using Spring Webflow, I am calling the OXMapper functions and passing the ACORD(hierarchical structural as it is used to build xml) object to it. This OXMapper class is responsible for marshalling and unmarshalling of the object and xml respectively.
Now the problem is whenever I am searching again on search page , old values automatically populates inside the fields.
So I tried changing the scope to "Request".
<bean id="acordRequest" class="com.abc.xyz.cate.domain.ACORD"
    scope="request">
    <property name="insuranceSvcRq" ref="insuranceSvcRq" />
    <property name="signonRq" ref="CltSearch_signonRq" />
</bean>

After changing the scope I get the following error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'oXMapper' defined in ServletContext resource [/WEB-INF/config/app-config.xml]: Cannot resolve reference to bean 'acordRequest' while setting bean property 'acordRequest'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'acordRequest': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

My web.xml is as follows
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/config/web-application-config.xml
    </param-value>
</context-param>
<error-page>
    <error-code>500</error-code>
    <location>/error.xhtml</location>
</error-page>
<context-param>
    <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
    <param-value>.xhtml</param-value>
</context-param>
<context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Development</param-value>
</context-param>
<context-param>
    <param-name>facelets.DEVELOPMENT</param-name>
    <param-value>true</param-value>
</context-param>
<context-param>
    <param-name>javax.faces.FACELETS_REFRESH_PERIOD</param-name>
    <param-value>1</param-value>
</context-param>
<context-param>
    <param-name>javax.faces.FACELETS_LIBRARIES</param-name>
    <param-value>/WEB-INF/springsecurity.taglib.xml</param-value>
</context-param>
<!-- Enables Spring Security -->
<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
    <listener-class>
        org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<listener>
    <listener-class>
        org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
<servlet>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value></param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <url-pattern>/certs/*</url-pattern>
</servlet-mapping>
<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.faces</url-pattern>
</servlet-mapping>
<welcome-file-list>
    <welcome-file>index.html</welcome-file>
</welcome-file-list>

My faces-config.xml has nothing as such
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">

<application>
    <!-- <message-bundle>JsfMessageResources</message-bundle> -->
</application>
<!-- JSF 2.0 Version of this faces-config.xml file -->

A: If you are not using Spring MVC, in order to use the request scope, you must reference the RequestContextListener in your web.xml:

f you use a Servlet 2.4+ web container, with requests processed outside of Spring's DispatcherServlet (for example, when using JSF or Struts), you need to add the following javax.servlet.ServletRequestListener to the declarations in your web applications web.xml file:

<web-app>
...
<listener>
  <listener-class>
      org.springframework.web.context.request.RequestContextListener
  </listener-class>
</listener>
...
</web-app>

Quote from docs.


text:
Q: Enum: type name is not allowed I am a .Net C# programmer trying to program in C++. I have an application that uses a third party library. When i try and use an Enum from the library in a function for this library I get an error message of type not allowed:
I have included the library:
#include <Trading.h>

using namespace Trading;

Trading.h includes Enumerations.h that contains:
/// Returns string representation.
FOO std::string enumToString (TimeInForce::Enum);

/// Trading session event type.
struct FOO TradSesEvent
{
    /// @copydoc TradSesEvent
    enum Enum
    {
       ...
    };
};

Code of the Application.cpp simplified to the problem:
#include <Trading.h>

using namespace Trading;

class Application
{
public:
    Application(const Settings& settings) : settings_(settings)
    {
        orderBook_.reset(new OrderBook());
    ...
    }

private:
    // Store of orders sent to counterparty.
    PtrTraits<OrderBook>::UniquePtr orderBook_;

    void onSendNewOrder(Order& newOrder)
    {
        //create unique_ptr to fill in the order values and sen

        PtrTraits<Order>::UniquePtr order(new Order(orderBook_->newId()));

        order->timeInForce = TimeInForce.Day;
        ...
    }
};

Error message:

struct Application::TimeInForce type name is not allowedC/C++(254)

A: The syntax for naming a member of an unscoped enum declared in a class or namespace TimeInForce is:
TimeInForce::Day

The period (.) is used for accessing non-static members of classes.


text:
Q: One static height div and 2 flexible height divs inside container I'm creating a small chat for my site.

What my end result should look like is something like this:
http://jsfiddle.net/XXHTC/2/
This is pretty easy when I know the height of the user div. However, the user div does not have a known height, it expands and shrinks as users log on and off.
The chatform at the bottom has a known height, so I can set position absolute and bottom: "height of chatform div" to it's height so the chat does not overlap it.
How can i set the "top" value of chat relative to the user div as it expands/shrinks.
Don't want the user div to hide anything in the chat div.

A: You'll need to use JavaScript to determine the height of div#user and then set the top position of div#chat equal to that height.
Demo


text:
Q: Haskell/Trifecta: Parsing completely optional semicolons without polluting AST I have rewritten the question since it was originally posted with a more concise code example:
Consider a language with fully optional semicolons almost entirely as sugar, i.e.:

*

*;; foo; bar;;;; is valid

*foo bar foobar is valid

*if (+1); foo is different to if (+1) foo in semantics, so ; cannot be considered whitespace

Here is an example parser:
{-# LANGUAGE OverloadedStrings #-}

import Text.Trifecta
import Text.Trifecta.Delta
import Text.PrettyPrint.ANSI.Leijen (putDoc, (<>), linebreak)
import Control.Monad.Trans.State.Strict
import Control.Applicative

type TestParser a = StateT Int Parser a

data AST a = Foo a | Bar a deriving (Show)

pFoo :: TestParser (AST (Delta, Int))
pFoo = curry Foo <$ string "foo" <*> position <* modify (+1) <*> get

pBar :: TestParser (AST (Delta, Int))
pBar = curry Bar <$ string "bar" <*> position <*> get

pStmt :: TestParser (AST (Delta, Int))
pStmt = semi *> pStmt <|> pFoo <|> pBar <?> "statement"

pTest :: TestParser [AST (Delta, Int)]
pTest = some pStmt

main :: IO ()
main
 = do   let res = parseByteString (evalStateT pTest 0)
                    (Directed "(test)" 0 0 0 0) ";;foo;bar;\nfoo;; foobarbar;;"
        case res of
            Success ast
             -> print ast
            Failure errdoc
             -> putDoc (errdoc <> linebreak)

The problem I am having with such a parser is that I need to be able to skip over semicolons without committing to parse a pStmt. At the moment the following error occurs:
(test):2:18: error: unexpected
    EOF, expected: statement
foo;; foobarbar;;<EOF>

This is because it expects a statement (in semi *> pStmt), however because stacked semicolons can sugar both the beginning and end of expressions I can't be sure I really want to expect/parse one before I already expect one.
One hack I developed was to have Nop as a constructor in my AST, but I really don't want to do that -- it feels like a hack and with the number of semicolons in some documents it would greatly increase memory usage.
I am looking for solutions/suggestions.

Attempt at EBNF form of the desired grammar:
expr = "foo" | "bar"
expr with sugar = expr | ";"
program = { [white space], expr with sugar, [white space] }

A: Ok, here it is:
pStmt = pFoo <|> pBar

pWhiteStmt = do
    many whitespace
    p <- pStmt
    many whitespace
    return p

pTest = do
    many semi
    pS <- sepEndBy pWhiteStm (some semi)
    eof
    return pS

And test it:
> parse pTest "" ";;foo;bar;\nfoo;; foo;bar;bar;;"
Right ["foo","bar","foo","foo","bar","bar"]

> parse pTest "" ";;foo;bar;\nfoo;; foobarbar;;"
Left (line 2, column 10):
unexpected 'b'
expecting ";" or end of input

If we wish to have a valid "; foobarbar;", then we need to change pWhiteStmt parser to next:
pWhiteStmt = do
    many whitespace
    p <- some pStmt
    many whitespace
    return p

And check it:
> parse pTest "" ";;foo;bar;\nfoo;; foobarbar;;"
Right [["foo"],["bar"],["foo"],["foo","bar","bar"]]

And finally, if we still wish to have valid "; foo  bar baz;" then we also need to change pTest function to next:
pTest = do
    many semi
    pS <- sepEndBy (some pWhiteStm) (some semi)
    eof
    return pS

And test it
> parse pTest "" ";;foo;bar;\nfoo;; foo bar bar;;"
Right [[["foo"]],[["bar"]],[["foo"]],[["foo"],["bar"],["bar"]]]

If we have many parentheses , it is need to replace return p to return (concat p) in the pWhiteStmt


text:
Q: ERR_HTTP_HEADERS_SENT - Express: headers cannot be set after they are sent to the client, how can i solve this error? I've try a lot's of different solution on stackoverflow about this but. But they didn't work.
It raise this error:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
      at ServerResponse.setHeader (_http_outgoing.js:485:11)
      at ServerResponse.header (/mnt/c/Users/Lucas-PC/Desktop/OnlineChat/node_modules/express/lib/response.js:771:10)         at ServerResponse.location (/mnt/c/Users/Lucas-PC/Desktop/OnlineChat/node_modules/express/lib/response.js:888:15)       at ServerResponse.redirect (/mnt/c/Users/Lucas-PC/Desktop/OnlineChat/node_modules/express/lib/response.js:926:18)       at Statement. (/mnt/c/Users/Lucas-PC/Desktop/OnlineChat/app.js:135:28)
  --> in Database#each("SELECT * FROM users WHERE email='yyyy@yyyy'", [Function])
      at /mnt/c/Users/Lucas-PC/Desktop/OnlineChat/app.js:133:16
      at Layer.handle [as handle_request] (/mnt/c/Users/Lucas-PC/Desktop/OnlineChat/node_modules/express/lib/router/layer.js:95:5)
      at next (/mnt/c/Users/Lucas-PC/Desktop/OnlineChat/node_modules/express/lib/router/route.js:137:13)
      at Route.dispatch (/mnt/c/Users/Lucas-PC/Desktop/OnlineChat/node_modules/express/lib/router/route.js:112:3)
      at Layer.handle [as handle_request] (/mnt/c/Users/Lucas-PC/Desktop/OnlineChat/node_modules/express/lib/router/layer.js:95:5)
      at /mnt/c/Users/Lucas-PC/Desktop/OnlineChat/node_modules/express/lib/router/index.js:281:22
      at Function.process_params (/mnt/c/Users/Lucas-PC/Desktop/OnlineChat/node_modules/express/lib/router/index.js:335:12)
      at next (/mnt/c/Users/Lucas-PC/Desktop/OnlineChat/node_modules/express/lib/router/index.js:275:10)
      at /mnt/c/Users/Lucas-PC/Desktop/OnlineChat/app.js:70:5 {
    code: 'ERR_HTTP_HEADERS_SENT',
    __augmented: true
  }

Here is my code:

const redirectLogin = (req, res, next) => {
    if (!req.session.userId){
        res.redirect('/login');
    }else {
        next();
    }
}

const redirectHome = (req, res, next) => {
    if (req.session.userId){
        res.redirect('/dashboard');
    }else {
        next();
    }
}

app.post('/login', redirectHome, (req, res) => {
    reloadUsers(users);
    const { email, password } = req.body;
    if (email && password) {
        const user = users.find(user => user.email === email && user.password === password) // TODO: hash password
        if (user){
            console.log(user.id);
            req.session.userId = user.id;
            res.redirect('/dashboard');
            return;
        }
    }
    res.redirect('/')
})

app.post('/register', redirectHome, (req, res) => {
    const { name, job, email, password } = req.body;

    if (name && job && email && password){ // TODO: validation more complex
        const exists = users.some(user => user.name === name && user.email === email);

        if(!exists){
            let infos = [name, email, job, password];
            let placeholders = infos.map((info) => '?').join(',');
            let sql = 'INSERT INTO users(name, email, job, password) VALUES('+ placeholders +')';
            db.run(sql, infos);
            console.log('email: '+req.body.email);
            db.each("SELECT * FROM users WHERE email='"+req.body.email+"'", (err, row) => {
                req.session.userId = row.id;
            })
            return res.redirect('/dashboard');
        }
    }

    res.redirect('/');
})

app.post('/logout', redirectLogin, (req, res) => {
    reloadUsers(users);
    req.session.destroy(err => {
        if (err){
            return res.redirect('/dashboard');
        }
        res.clearCookie(SESS_NAME);
        res.redirect('/login');
    });
})

I think the error come from the app.post('/login') and app.post('/register') on the res.redirect('/dashboard')

A: Under your /register router, you are trying to set the request after response is sent.
db.each("SELECT * FROM users WHERE email='"+req.body.email+"'", (err, row) => {
    req.session.userId = row.id;
})
return res.redirect('/dashboard');

db.each() is an asynchronous function so you would have to handle response within the function.
db.each("SELECT * FROM users WHERE email='"+req.body.email+"'", (err, row) => {
    req.session.userId = row.id;
    return res.redirect('/dashboard');
})

SOME TIPS: Also try to escape your strings when you are constructing SQL statements to avoid SQL injections.


text:
Q: Enable AirPrint on HP LaserJet M1212nf MFP I am attempting to be able to AirPrint from my iOS devices (iPad 3rd gen, iPod touch 4th, iPhone 5, etc) to my existing LaserJet. I have read that this is possible with this printer.
My configuration is as follows:

*

*The printer is an HP LasertJet M1212nf MFP

*This printer is connected to my iMac running Mountain Lion through USB

*The iMac is connected to my home wireless network over WiFi

*The iOS devices are all running latest iOS versions

Thanks for any help!

A: You need to have the printer on the network, as opposed to shared from your iMac.  Plug the printer into your wireless router via the RJ45 (network cable) port.
If everything works as expected, your iOS devices will just see it when they are on the same wireless network.
If not, you'll need to go through the menus and configure the printer.
Any other devices using the printer currently (e.g. the iMac) will need to be configured to use the printer via the network, as opposed to the share you have off the iMac.


text:
Q: How can I determine if an Oracle table has the ROWDEPENDENCIES option set? I only have the basic Oracle tools available, i.e. SQL Plus, and I need to find out if a table was created with the ROWDEPENDENCIES option. It's a 10g database.
And, if it isn't set, can I use ALTER TABLE to set it, or do I have to drop and re-create the table?

A: SELECT owner, table_name, dependencies FROM dba_tables;

This will return "ENABLED" or "DISABLED" for each table. If you don't have access to dba_tables, query all_tables instead.
You cannot change this after the table has been created, so you'll have to re-create the table to set it on.


text:
Q: Return statements How do I get this code to work? I need to return the statements from the 3 scenarios, currently I'm getting an error at String robotInfo.
String generateStatusReport(Robot robot) {

    String robotStatus;
    String robotWall;
    String robotGround;
    String robotInfo = robotStatus + robotWall + robotGround;

    if(isRobotDead(robot)) {
        robotStatus = ("The robot is dead.");
    } else {
        robotStatus = ("The robot is alive.");
        if(isRobotFacingWall(robot)) {
            robotWall = ("The robot is facing a wall.");
        } else {
            robotWall = ("The robot is not facing a wall.");
        }

        if(isItemOnGroundAtRobot(robot)) {
            robotGround = ("There is an item here.");
        } else {
            robotGround = ("There is no item here.");
        }
    }
    return robotInfo;
}

A: I would move your concatenation to after the conditional but before the return statement:
String generateStatusReport(Robot robot) {

    String robotStatus;
    String robotWall;
    String robotGround;

    if(isRobotDead(robot))
        robotStatus = ("The robot is dead.");
    else {
        robotStatus = ("The robot is alive.");
        if(isRobotFacingWall(robot))
            robotWall = ("The robot is facing a wall.");
        else
            robotWall = ("The robot is not facing a wall.");

        if(isItemOnGroundAtRobot(robot))
            robotGround = ("There is an item here.");
        else
            robotGround = ("There is no item here.");
    }
    String robotInfo = robotStatus + robotWall + robotGround;
    return robotInfo;
}

Or just return the concatenation:
return robotStatus + robotWall + robotGround;

A: You need to initialize your strings to get a value in robotInfo
String robotStatus;
    String robotWall;
    String robotGround;


text:
Q: Making Linux unzip command just extract files from directories whose names contain a given string I have a zip archive that contains a directory hierarchy of files. I want to use the Linux unzip command to extract just the subset of these files that have a particular string somewhere in the directory path leading up to the file.
For example, suppose the file foo.zip contains these files:
a/1.txt
acme/2.txt
a/acme/b/3.txt
a/b/acmenet/c/4.txt
a/b/c/5.txt
a/acme/d/6.php

The Linux command "unzip foo.zip *.txt" will extract all 5 of the "txt" files.
How can this Linux command be modified so that it only extracts the 3 "txt" files that have the string "acme" somewhere in the directory path (so it would extract only 2.txt, 3.txt and 4.txt)?

A: Your example unzip foo.zip *.txt only worked because there was no *.txt file in your working directory. Otherwise *.txt
would have been expanded by the shell to the names of the text files in your directory. You need to quote it to be on the safe side.
Since unzip uses globs, use
unzip foo.zip '*acme*/*.txt'

or even
unzip foo.zip '*acme*.txt'

If you don't want to restore the original directory structure and extract the files to the current working directory, add option -j:
unzip -j foo.zip '*acme*/*.txt'


text:
Q: jQuery .scroll to change background like a movie I am trying to change the background image of webpage using 200 images and play them like a movie. My code is working, however the transition is flickering when the picture changes on scroll. Seems that during the scroll the CSS is updated and I get a flicker. It is very noticeable in Chrome and Safari, but also does it in FF. Seems smoother in FF. Strange. Need help smoothing things out. I am using the following code below. Please, any help in smoothing out the transition and making it more movie like would be great. I am new to jquery, but have a background in programming. Any and all advice is greatly appreciated!
I have researched for nearly three days. Some have mentioned that updating the .htaccess file helped so that the header of the files are set to not expire and the browser is sending a 304. I dont know how to test, but here is my code below.
var pics = []; // CREATE PICS ARRAY

    //PRELOAD FUNCTION TO SET UP PICS ARRAY IN MEMORY USING IMAGE OBJECT
function preload(){
    for(i = 0; i < arguments.length; i++) {
        pics[i] = new Image();
        pics[i].src = arguments[i];
    }
};
preload(
'bgImage/1.jpg'
,'bgImage/2.jpg'
,'bgImage/3.jpg'
,'bgImage/4.jpg'
,'bgImage/5.jpg'
); // THERE ARE 200 TOTAL IMAGES THAT WE ARE LOADING...

function switchImage() {
var s = $(window).scrollTop();
var index = 0;
if(s>   10  ){index =   1   ;}
if(s>   20  ){index =   2   ;}
if(s>   30  ){index =   3   ;}
if(s>   40  ){index =   4   ;}
if(s>   50  ){index =   5   ;}
// THERE IS 200 IF STATEMENTS IN TOTAL
// THE ODER OF THE IMAGES STARTS IN THE MIDDLE AND WE HAVE TO ADJUST DEPENDING ON POSITION
// USING THE IF STATEMENTS WAS THE EASIEST SOLUTION
$("body").css('background-image', 'url(' + pics[index].src + ')');
};

$(document).ready(function () {
switchImage();
//alert("images and dom loaded");
});

$(window).scroll(function () {
switchImage();
});

A: If your images are named #.jpg wrap preload function into adapter that recieves number of images and iterates preload string like 'bgImage/' + i + '.jpg'.
This way you can immediately get reusable array to use on scroll in combination with switch statement for all 200 segments, which is real pain in the A... or just invoke :
index = $(window).scrollTop()/10;

This single line should replace all of your indexes, and every time you scroll you will put the right image into background.
As for changing css on javascript/jQuery event, I recommend using jQuery animate with really quick transition of couple ms, but stil a transition.


text:
Q: AC-DC power supply burning relays I use an Arduino to control a relay. This relay is on an 8-relay board. The relays are rated at 120 VAC, 10 A.
This relay powers on and off an AC-DC power supply. It has 110 V AC input and is rated at 12 V DC, 20 A.
The load is an LED strip. I have already 7 or 8 burned relays from different LED strips. It doesn't matter if it is a 1 m long LED strip or a 16 m long led strip. The current, in both cases, is below the rated 20 A of the power supply.
The relays usually stop working when turning on or off the relay. Just one stops working. The other relays on the board are still operational.
I'm pointing at the power supply as the the guilty one here as I have hundred other loads that didn't burn. And some of the loads are higher than this power supply.
What could be causing it? How can I avoid more relays being burned? Is there a "diode" for AC that could stop it from burning? Do you see anything else besides the power supply that could be causing it?

PS: By burning I mean that it just stops working.
EDIT: The relay board is a cheap AliExpress 8-relay board. The relays are JQC-3FF-S-Z. The datasheet that I found is: https://www.digikey.com/htmldatasheets/production/2071105/0/0/1/jqc-3ff.html
EDIT 2: for future internet users, as described on the answers below, the issue was with the surge current. I bought new power supplies that had a NTC thermistor device in series with the AC line. It takes a few seconds to turn on the Led Strip, but I guess that's better than burning relays.

A: You should never use dry relay contacts on a power supply input that are not rated for the surge current of charging the capacitor and the inductive stored energy on flyback when shutting it off.
These surges greatly exceed the rated current.
You can however use it to control a resistive load like LEDs as long as it is within the current rating.
Many DC supplies also have an enable control for a logic level or contact closure enable.
Cycling the power supply also adds stress to the supply. Consider if it has a soft start circuit but is cycled too fast and does not have protection.
Most power supplies have a varied lifespan of power cycles due to the added random phase current surge. Your mileage may vary.
PC's have been designed this way for some time to use only a soft logic power switch.
The datasheet of your relay link shows what happens with high surge currents on lifespan. No surprise here.
Although OMRON Relays were 10x better.

A: The root cause of your relay failure is the high input surge current of the DC power supply due to capacitor charging at cold-start.
You would need to select a relay, from 'high-inrush current' models, considering the TV rating mentioned in the data sheet.
The TV rating, as per UL and CSA standards, is an assessment of the inrush current withstanding capability of relay contacts as follows:
TV3 - 51A, TV4 - 65A, TV5 - 78A and TV8 - 117A, TV10 - 141A, TV15 - 191A.
The 120V, 240W (12 V * 20 A), power supply, that you have used, could have an inrush current of the order of 150 A.
Hence the relay would need to have a rating of TV10 or TV 15.
The relay you are using has a rating of TV5 only.


text:
Q: Jekyll Build Not Working after MacOS High Sierra Update Not sure if this is a bug, but I wasn't able to find anything on the Web. Everything was working fine using a combination of Grunt, Jekyll and Homebrew to create my website. But once I updated to High Sierra the Jekyll build fails.
The way I usually run Jekyll build is via grunt-shell task like so:
grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        shell: {
            jekyllBuild: {
                command: 'jekyll build'
            }
        },
       connect: {
            server: {
                options: {
                    hostname: 'localhost',
                    port: 4000,
                    base: '_build'
                }
            }
        },
...
      watch: {
            jekyll: {
                options: {
                    livereload: true
                },
                files: [
                    '**/*.scss',
                    '**/*.html',
                    '**/*.js',
                    // The negations must go after
                    '!*node_modules/**',
                    '!*_build/**',
                    '*.md',
                    '*.yml',
                    'img/**',
                    ],
                tasks: ['shell:jekyllBuild','postcss']
            }
        }
    });

...

grunt.registerTask('serve', ['shell','connect','watch']);

Which gives the following error:
Running "shell:jekyllBuild" (shell) task
Configuration file: [URL]/_config.yml
            Source: [URL]
       Destination: _build
 Incremental build: disabled. Enable with --incremental
      Generating...
jekyll 3.6.0 | Error:  negative argument
Warning: Command failed: jekyll build
 Use --force to continue.

Aborted due to warnings.

Everything else I run works except Jekyll.
I also tried just running jekyll build without shell task but still got an error:
jekyll 3.6.0 | Error:  negative argument
Warning: Command failed: jekyll build
 Use --force to continue.

Aborted due to warnings.

I am using Homebrew to keep things local and everything seems to be in the correct location:
~$ which jekyll
/usr/local/bin/jekyll
~$ which ruby
/usr/local/bin/ruby
~$ which grunt
[URL]/.npm-packages/bin/grunt
~$ which gem
/usr/local/bin/gem
~$ which node
/usr/local/bin/node

I realize, my setup may not be the best, but it was working so I'm hoping for some guidance. I was not the one to initially create this setup and I'm not a programmer but rather a web designer who can hack things together to my own detriment at times :)

A: The issue ended up not being related to OS update, but rather a custom Jekyll plugin that was causing the issue. Once the plugin was removed everything worked. However, something did change perhaps in Jekyll or elsewhere to make the plugin not work all of the sudden. I will open a separate issue to figure that out. Thanks @Casper and @JoostS for quick responses.


text:
Q: Attempt to invoke virtual method 'java.io.File com.client.bw.aali.com.activities.cache.MyApplication.getCacheDir()' on a null object reference When i wil check the whole code into activity then its work fine when past into fragment i'm getting this error
public class ServiceGenerator {

    private static final String TAG = "ServiceGenerator";
    public static final String HEADER_CACHE_CONTROL = "Cache-Control";
    public static final String HEADER_PRAGMA = "Pragma";

    private static ServiceGenerator instance;

    public static ServiceGenerator getInstance(){
        if(instance == null){
            instance = new ServiceGenerator();
        }
        return instance;
    }

    private static final long cacheSize = 5 * 1024 * 1024; // 5 MB

    private static Retrofit retrofit(){
        return new Retrofit.Builder()
                .baseUrl(Config.BASE_URL)
                .client(okHttpClient())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    private static OkHttpClient okHttpClient(){
        return new OkHttpClient.Builder()
                .cache(cache())
                .addInterceptor(httpLoggingInterceptor()) // used if network off OR on
                .addNetworkInterceptor(networkInterceptor()) // only used when network is on
                .addInterceptor(offlineInterceptor())
                .build();
    }

    private static Cache cache(){
        return new Cache(new File(MyApplication.getInstance().getCacheDir(),"someIdentifier"), cacheSize);
    }

    /**
     * This interceptor will be called both if the network is available and if the network is not available
     * @return
     */
    private static Interceptor offlineInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Log.d(TAG, "offline interceptor: called.");
                Request request = chain.request();

                // prevent caching when network is on. For that we use the "networkInterceptor"
                if (!MyApplication.hasNetwork()) {
                    CacheControl cacheControl = new CacheControl.Builder()
                            .maxStale(7, TimeUnit.DAYS)
                            .build();

                    request = request.newBuilder()
                            .removeHeader(HEADER_PRAGMA)
                            .removeHeader(HEADER_CACHE_CONTROL)
                            .cacheControl(cacheControl)
                            .build();
                }

                return chain.proceed(request);
            }
        };
    }

    /**
     * This interceptor will be called ONLY if the network is available
     * @return
     */
    private static Interceptor networkInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Log.d(TAG, "network interceptor: called.");

                Response response = chain.proceed(chain.request());

                CacheControl cacheControl = new CacheControl.Builder()
                        .maxAge(5, TimeUnit.SECONDS)
                        .build();

                return response.newBuilder()
                        .removeHeader(HEADER_PRAGMA)
                        .removeHeader(HEADER_CACHE_CONTROL)
                        .header(HEADER_CACHE_CONTROL, cacheControl.toString())
                        .build();
            }
        };
    }

    private static HttpLoggingInterceptor httpLoggingInterceptor ()
    {
        HttpLoggingInterceptor httpLoggingInterceptor =
                new HttpLoggingInterceptor( new HttpLoggingInterceptor.Logger()
                {
                    @Override
                    public void log (String message)
                    {
                        Log.d(TAG, "log: http log: " + message);
                    }
                } );
        httpLoggingInterceptor.setLevel( HttpLoggingInterceptor.Level.BODY);
        return httpLoggingInterceptor;
    }

    public static WebServices getApi(){
        return retrofit().create(WebServices.class);
    }

}

*

*Locat
java.lang.NullPointerException: Attempt to invoke virtual method
'java.io.File
com.client.bw.aali.com.activities.cache.MyApplication.getCacheDir()'
on a null object reference
at com.client.bw.aali.com.activities.cache.ServiceGenerator.cache(ServiceGenerator.java:61)
at com.client.bw.aali.com.activities.cache.ServiceGenerator.okHttpClient(ServiceGenerator.java:53)
at com.client.bw.aali.com.activities.cache.ServiceGenerator.retrofit(ServiceGenerator.java:46)
at com.client.bw.aali.com.activities.cache.ServiceGenerator.getApi(ServiceGenerator.java:134)
at com.client.bw.aali.com.activities.listView.fragments.ListViewFragment.setAdapter(ListViewFragment.java:141)
at com.client.bw.aali.com.activities.listView.fragments.ListViewFragment.onCreateView(ListViewFragment.java:98)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2963)


text:
Q: Give an example of a simply ordered set without the least upper bound property. In Theorem 27.1 in Topology by Munkres, he states "Let $X$ be a simply ordered set having the least upper bound property.  In the order topology, each closed interval in $X$ is compact."
(The LUB property is if a subset is bounded above, then it has a LUB.)
I don't understand how you could have a simply ordered set (a chain) WITHOUT the LUB property.  If a subset is bounded and it is a chain, then how can it not have a LUB?
Can someone give an example?
Thanks!

A: $\Bbb Q$
Added: $\{q\in\Bbb Q:q<\sqrt2\}$ is a chain, it's bounded above by $2$, say, and it has no least upper bound in $\Bbb Q$, because $\sqrt2$ is irrational.

A: Consider $(-1,0)\cup(0,1)$ with the natural ordering (which is linear). $(-1,0)$ has no least upper bound although it is bounded (eg. by $1/2$).

A: $\{0,1\}\times\Bbb Z$ ordered lexicographically. The subset $\{0\}\times\Bbb N$ is bounded from above but has no least upper bound.

A: Up to isomorphism, the minimal example is the set
$$
\left\{-\frac{1}{n}\;;\;n\geq 1\right\}=-\frac{1}{\mathbb{N}^*}\quad\mbox{in}\quad\frac{1}{\mathbb{Z}^*}=\left\{\frac{1}{n}\;;\;|n|\geq 1\right\}
$$
with the obvious ordering.

A: According to the strict definitions given by the OP, the null set fails to have a Least Upper Bound while still being simply ordered.
The Least Upper Bound of a set, as defined at the Wikipedia page he links to requires that it be a member of that set.  The null set, having no members, clearly lacks a LUB.
However, the definition given for being simply ordered does not require that the set have any elements.  Indeed, a set can only lack the property if it has a pair of elements that are not comparable.
So, the null set is indeed Simply Ordered without having the Least Upper Bound property.

A: Perhaps your source of confusion is this: if a chain has a greatest element then that serves as a least upper bound, since it is an upper bound (since it is greatest) and is less than or equal to any upper bound for the chain because it's an element of it.
However! Not every chain need have a greatest element! Here's how you might think about this:
Depending on your level of pedantry, you may regard the empty set as a chain (every pair of elements from it is orderable, after all). Then certainly it doesn't have a greatest element, since it has no elements at all. Does it have a least upper bound? Well, every element of the poset is trivially an upper bound for the empty set, so a least upper bound is precisely a least element. We'll assume the poset itself is non-empty, so that the empty set does have an upper bound. Let's call it $u_0$. How can this upper bound fail to be least? Well, there must be another upper bound smaller than it, say $u_1 < u_0$. Likewise, there must be another upper bound smaller than that, and so on: you must have an infinite descending chain $u_0 > u_1 > u_2 > \dots$ and as long as there's nothing below the entire chain, there can't be a least element. The negative integers are the most obvious example.
So if you accept the empty chain as a chain, in the simply ordered set of the negative integers it has upper bounds but no least upper bound.
But that's not terribly satisfying. What about non-empty chains? Well, suppose your poset has an element $x_0$. One of two things can happen: either $x_0$ is maximal for the chain, or some $x_1$ has $x_1 > x_0$. Is $x_1$ maximal? Maybe, or maybe there's an $x_2 > x_1$, and so on. If this set is to avoid having a maximal element (hence a least upper bound) it must go upwards forever – an ascending chain. It should be bounded – okay, just invent an element that goes above the entire ascending chain. But it can't have a least upper bound – this precisely means the set of upper bounds can't have a least element, and as we discussed before that basically means we need an infinite descending chain.
So if we have an infinite ascending chain of elements, and an infinite descending chain of upper bounds for it, we'll fail to have a least upper bound again.
The lesson to be learnt here is that posets are very flexible structures, and you can form one by just listing elements and placing them relative to each other: it's not like, say, a group, where there is quite a lot of rigidity to the structure, or a field, where you get barely any choice at all.
Indeed, one possible approach would be to take the real numbers, find a subset $C$ with a least upper bound $u$, but $u \not \in C$. Form a new poset by removing $u$ from the reals. Now $C$ doesn't have a least upper bound anymore!

A: One more answer, not discussed till now.
Consider $A = \{x,y,z\}$. So $\mathbb{P}(A)=  \{\phi, \{x\}, \{y\}, \{z\}, \{x, y\}, \{y,z\}, \{x, z\}, A\}$.
Consider partial order relation $<$ on $\mathbb{P}(A)$ as $a<b$ iff $a\subset b$.
Consider the element $\phi \in \mathbb{P}(A)$. See nay element of $\mathbb{P}(A)$ is an upper bound of the set $\phi$. What is the least upper bound ? Not exists.