text:
Q: "Led Zeppelin was" vs. "Led Zeppelin were"
Led Zeppelin were an English rock band formed in London in 1968.

(Source.)
Is "were" really the right word here? It feels like it should be "was".
After reading the answers and my own searching, it appears to be correct in this case
Should I use American English or British English?

A: "Led Zeppelin were..." would be considered improper in US English, but in the UK, names of groups, organizations, and companies are often treated as plural:

[T]he Government have taken £4.5bn from the mineworkers' pension scheme...

In this context, "Led Zeppelin were..." would be appropriate.

A: The Beatles were... You are talking about a group of musicians under the name of Led Zepelin so the plural verb fits.
But The Band of Led Zepelin was ...verbs with group names is always tricky.
The link might help:
http://www.oxforddictionaries.com/us/words/matching-verbs-to-collective-nouns-american


text:
Q: How does a circuit "know" the resistance? This is obviously a very basic question, I'm pretty new to concepts of circuitry and so on. So, lets say you have a circuit with simply a battery, a resistor, and a multimeter measuring the current.
From my understanding, the circuit almost, well, knows(?) the resistance before any current travels. Obviously that's not really possible. But could someone shed some light on how this works? Thanks a ton.

A: It does NOT know in advance.
When you connect a resistor to a battery, current starts to flow from zero and quickly ramps up until the voltage across the load (the resistor) matches the voltage of the battery.
Voltage Across Resistor = Current x Resistance Value

When that happens the current can no longer grow. It balances out.
NOTHING ever happens instantaneously. But it happens so fast in human terms, it appears that way.
Actually the math is a bit more complicated than that.. but it boils down to the same thing.

redpajama_set_name: RedPajamaStackExchange


text:
Q: refers to usage of Today, things aren't always as clear online. Spotting the word "tonight" or "yesterday" in an article you've arrived at via search, you likely have to scroll back to the top of the page or peek at the URL to figure out how old the story is. By the time you figure out that "tomorrow" means "yesterday," because this story is two days old, you've probably lost track of what you were reading and you're ready to click away.
The best practice is to clearly identify the day of the week. Here's how it's put in the B/R Stylebook:

Days of the week (e.g. Monday) should be clearly identified in all contexts. Avoid potentially confusing references like "tonight" and "tomorrow" that would force a reader to check the submission date atop the article. Note that words like "today" and "tomorrow" may be used in quotations or in expressions that do not refer to a specific date.

That last phrase refers to usage of "today" in the sense I used it a few paragraphs ago, meaning "these days.
Reference

I'm not sure if "usage" means "the act of using the word" or "the way the word is used in a language".

A: It means the former: the act of using a word. He is talking about writers using that word ("today") in news articles, opinion pieces, etc.


text:
Q: Windows 10 : Windows seems to create an empty Local drive after boot My Windows 10 creates an empty (size 0) Drive (Q:, seen as a local drive), on which I have no access right, even as Administrator.
When I go in This Computer > Manage > Storage > Disk Manager this Disk does not appear.
This does not occur when I restart in Safe Mode.
Only 2 Avast Softwares are Enabled on Boot in the Task Manager.
Any idea what kind of Program could be creating an empty virtual Hard drive at Boot ?
May be Related : I also have a "How do you want to open this Program" that I can't fix, because I have nothing more than the above enabled at boot so I don't understand where the problem come from.

A: The Q: drive is the virtual file system drive where virtualized applications are located in the file system namespace. This Q: drive is not a typical drive. The Q: drive has no space that the user can access directly and is inaccessible from Windows Explorer or My Computer.
This drive does not show up as a result of Windows 10, nor is it a Windows problem. Instead, this drive appears when a Click-to-Run version of Microsoft Office 2010 is installed.
https://support.microsoft.com/en-us/help/982434/an-overview-of-microsoft-office-click-to-run-for-office-2010


text:
Q: How should I design the stored proc and c # method to get such results I have a problem here.
In c# code I am constructing a method called
saveImages(Guid ImageId, String url, byte[] imageData) which calls a stored procedure to store the data on a sql server.
I understand all the process of how to construct a stored procedure and call it from c# code.
My question is, now I want the code to behave in such a way that if save successfully return the imageId otherwise return null.
How should I construct the stored procedure? How do I set the parameters?
And how do I get the returned value in C#?
Thanks

A: As already mentioned, you start by adding:
SELECT SCOPE_IDENTITY();

at the end of your Stored Procedure.
Your method should look something like:
public int saveImages(Guid ImageId, String url, byte[] imageData)
    {
      using (SqlCommand command = new SqlCommand() {
        Connection = your connection,
        CommandType = CommandType.StoredProcedure,
        CommandText = "your Stored Procedure"
      })
      {
        try
        {
          command.Parameters.AddWithValue(...); // Add your Parameters here
          return (int)command.ExecuteScalar();
        }
        catch
        {
          return 0;
        }
      }
    }


text:
Q: How to manage events in pyglet as Pygame? I do not understand completely how to use pyglet's event system. What I need to do is to get each event for each frame. In Pygame I can do it in the following way:
import sys, pygame
pygame.init()
size = width, height = 320, 240
screen = pygame.display.set_mode(size)
while 1:
    for event in pygame.event.get():
        print event
        if event.type == pygame.QUIT: sys.exit()
    screen.fill((0,0,0))
    pygame.display.flip()

I accomplish something similar with pyglet, using 'pyglet.window.event.WindowEventLogger()' but I do not how to acces to the information that the WindowEventLogger prints, and it prints the same event more than once.
How could I obtain a pyglet version of the pygame code above?

A: Here's a basic example of a working class that dispatches events.
#!/usr/bin/python
import pyglet
from time import time, sleep

class Window(pyglet.window.Window):
    def __init__(self, refreshrate):
        super(Window, self).__init__(vsync = False)
        self.frames = 0
        self.framerate = pyglet.text.Label(text='Unknown', font_name='Verdana', font_size=8, x=10, y=10, color=(255,255,255,255))
        self.last = time()
        self.alive = 1
        self.refreshrate = refreshrate

    def on_draw(self):
        self.render()

    def render(self):
        self.clear()
        if time() - self.last >= 1:
            self.framerate.text = str(self.frames)
            self.frames = 0
            self.last = time()
        else:
            self.frames += 1
        self.framerate.draw()
        self.flip()

    def on_close(self):
        self.alive = 0

    def run(self):
        while self.alive:
            self.render()
            event = self.dispatch_events() # <-- This is the event queue
            sleep(1.0/self.refreshrate)

win = Window(23) # set the fps
win.run()

However note that normally I never encounter any events at all in this event queue. Most likely because Pyglet works with function decorators/hooks.
So for instance, if you want to catch keyboard events, you would simply add the following code to this awesome class:
def on_key_release(self, symbol, modkey):
        print(symbol, modkey)

There's also on_mouse_motion etc :)


text:
Q: How to convert PNG to BMP at runtime? I need to convert PNG file to BMP file on runtime.
I can't do it like
Image dummy = Image.FromFile("image.png");
dummy.Save("image.bmp", ImageFormat.Bmp);

because i can't save the bmp image on the local disk as a file.
Thanks for any help.

A: You can save to stream
using(MemoryStream stream = new MemoryStream())
{
    Dummy.Save(stream, ImageFormat.Bmp);
}

A: Precise answer given here.
Image Dummy = Image.FromFile("image.png");
Dummy.Save("image.bmp", ImageFormat.Bmp);

Since you don't want to follow this method, you can do it the way Stecya answered.
Just do it this way.
Stream stream;
Dummy.save(stream, ImageFormat.Bmp)


text:
Q: Subtracting two point clouds? I have two point clouds (PCs): (i) PC-A (i.e. Reference PC or ground truth) and
(ii) PC-B (i.e. Bare-Earth PC obtained through filtering)
I want to subtract PC-B from PC-A to calculate commission and omission errors. So, far I tried computing cloud to cloud distances in cloudcompare, and then filtering points that are not within 0.05m threshold distance. However, since the topography is high variable, the aforementioned method is giving a huge spatial variation. I suspect that cloud-to-cloud distance isn't very accurate.
Is there any tool (preferably opensource and not too complex) that I could use to achieve PC-B (-) PC-A?

A: I believe what you are computing is called the "Hausdorff Distance."
https://en.wikipedia.org/wiki/Hausdorff_distance
There are other libraries you might try such as http://vcg.isti.cnr.it/vcglib/


text:
Q: jQuery autocomplete search and select programmatically I have a data from my controller and when the page loads I want the autocomplete input to search for that data and select it.
I am able to search the data using:
$( "#autocomplete" ).autocomplete( "search", '<?=$ID?>' );
above code works and showing the correct value of autocomplete. Now I cant select the value so that the autocomplete input triggers change. I wanted the input to trigger change because I will auto populate some input.
The way I select the value pro grammatically is :
select: function( event, ui ) {}
Now i found this:
search: function( event, ui ) {},
Is is possible to combine the two?
How to select searched data from auto complete programmatically ?
Update:
This is how my autcomplete works:
$( ".updatedautocomplete" ).autocomplete({
      source:function(request,response){
         var $this = $(this);
         $.post("url",{
            term:request.term
         }).done(function(data, status){
            response($.map( data, function( item ) {
                return {
                    data
                }
                return false; // Prevent the widget from inserting the value.
            }));

        });
      },
      select: function( event, ui ) {
         $( this ).attr( 'data-value' , ui.item.id );
         $( this ).attr( 'data-asd' , ui.item.sad );
         $( this ).val( ui.item.label );
         $( "#modal" ).val( ui.item.qwe.trim() );
         $( "#modal" ).val( ui.item.asd.trim() );
         $( "#modal" ).val( ui.item.zxc.trim() );
         $( "#modal" ).val( ui.item.ert.trim() );
         $( "#modal" ).val( ui.item.dfg.trim() );
        return false;
      }
    });

The reason why I wanted select event is to populate some input as shown in the source

A: You simply do jQuery.val() on the input element, like so.
Edit
Since you seem to want to trigger the selection after an asynchronous data retrieval, you probably want the response event and perform the selection there.
response (event, ui)

Triggered after a search completes, before the menu is shown. Useful for local manipulation of suggestion data, where a custom source option callback is not required. This event is always triggered when a search completes, even if the menu will not be shown because there are no results or the Autocomplete is disabled

$(".updatedautocomplete").autocomplete({
  source: function(request, response) {
    var $this = $(this);

    //$.post("url", {
    //  term: request.term
    //})
    //.done(function (data, status) {
    //  response($.map(data, function (item) {
    //      return {
    //        data
    //      }
    //      return false; // Prevent the widget from inserting the value.
    //    }));
    //
    //});

    // Simulates some data returned from server
    response([
      { label: "Javascript", value: "js" },
      { label: "CSharp", value: "cs" },
      { label: "PHP", value: "php" }
    ]);
  },
  response: function(event, ui) {
    // Make your preferred selection here
    var item = ui.content[0].label;

    $(this).val(item).trigger('change');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<input class="updatedautocomplete" />

search and select are the events which get triggered when the search is taking place. You don't execute them.
Additionally, I believe the method search (not the event one) is meant rather for "suggesting" users that a value/tag exists in the list and that they need to select it themselves. So, yes, if you need a value programmatically selected (without user interaction) you might need to do it by .val() and optionally .trigger().


text:
Q: Rails how to validate uniqueness across child objects with nested form In a nested form, I want the user to have the ability to create or modify all of a Parent's Childs at one time. So let's so the params that are passed are like this:
{"childs_attributes" => [{attribute:1}, {attribute:2}, {attribute:3}...]}

I would like a validation that says for any one Parent, the attributes of all of its Childs must be unique. In other words, in the above example, that's OK because you'd get:
Parent.childs.pluck(:attribute).uniq.length == Parent.childs.pluck(:attribute).length

However, if the params passed were like below, it'd be a violation of the validation rule:
{"childs_attributes" => [{attribute:1}, {attribute:2}, {attribute:3}...]}

So far the only solution I've come up with to do this validation is in the Controller...  which I know is bad practice because we want to push this to the model.
The problem is that if in the model I have something like the below:
class Parent
  validate :unique_attribute_on_child

  def unique_attribute_on_child
    attribute_list = self.childs.pluck(:attribute)
    if attribute_list.uniq.length != attribute_list.length
      errors[:base] << "Parent contains Child(s) with same Attribute"
    end
  end
end

That won't work because self.childs.pluck(:attribute) won't return the attribute passed in the current update, since the current update won't have saved yet.
I guess I could do something like an after_save but that feels really convoluted since it's going back and reversing db commits (not to mention, the code as written below [non tested, just an example] likely leads to a circular loop if I'm not careful, since Parent validate associated children)
after_save :unique_attribute_on_child

def unique_attribute_on_child
  attribute_list = self.childs.pluck(:attribute)
    if attribute_list.uniq.length != attribute_list.length
      self.childs.each { |c| c.update_attributes(attribute:nil) }
      errors[:base] << "Parent contains Child(s) with same Attribute"
    end
  end
end

Other ideas?

A: My first impulse is to suggest that Rails uses smart pluralization and to try using children instead of childs, but I think this was just the example.
I now recommend that you change your strategy. Call the validation on the children like so:
class Child < ActiveRecord::Base
  belongs_to :parent
  ...
  validates :child_attribute, uniqueness: { scope: :parent }
  ...
end


text:
Q: Access xmm registers in eBPF program I am trying to use bcc-tools to trace a user process using uprobe, but some functions take floating point arguments. According to x86_64 ABI, these values are normally passed in the xmm registers.
The eBPF functions in bcc takes a struct pt_regs * argument and in that I can get access to (a copy of ?) most "usual" registers, but not the xmm registers.
Is there a way to accomplish this ? Or is this something that was overlooked in the design of eBPF

A: TL;DR This is not an issue with BPF, neither uprobes nor kprobes can access AVX registers such as xmm registers.

uprobe programs are actually loaded in the kernel as kprobe programs (i.e., BPF_PROG_TYPE_KPROBE).
Contrary to most BPF programs, kprobe programs have access to an unmodified, unrestricted context argument at the hook point. What I mean is that the argument of BPF programs is often a mirror of the actual object given at the hook point, with accesses rewritten by the verifier. For example, several BPF programs take struct __sk_buff as argument, which is actually a mirror of sk_buff (see this other StackOverflow answer for more details). kprobe program, on the contrary, have access to the raw struct pt_regs object (the convert_ctx_access field of struct bpf_verifier_ops is null).
From this we can conclude that kprobes (which receive struct pt_regs) don't have access to the AVX registers. So it's a limitation of kprobes and not of BPF. One reason for this might simply be the low support for AVX registers in the kernel. Please see this StackOverflow answer for further information.


text:
Q: Use GS Query() to convert text value into a number Consider a table, in which column A is an entity associated with column B. And column B contains numbers in text formats (e.g., 3.0000 is a text).
I've tried this query:
=QUERY(range_name,"SELECT A, VALUE(B)",0).

I've also tried this query:
=QUERY(range_name,"SELECT A, B*1",0).

Neither works. I'm able within google sheets to convert it by multiplying (B*1), but I'd prefer to do this within the query.
Any ideas? I'm tagging SQL as well as google sheets, though quite a few SQL functions don't work in GS.
Thanks.

A: If you do it inside the range?
=QUERY({A:A,INDEX(VALUE(B:B))},"Select Col1, Col2",0)

Obviously if you just need the data without any further processing, you can get rid of "Select Col1, Col2" part


text:
Q: What is the difference betwen a time non-homogenous Markov Chain and a non-linear Markov Chain? Example A time non-homogenous Markov Chain is one in which the transition probabilities are not constant over time. A non-linear Markov Chain is a model that is not linear in parameters and satisfies the Markov property (independence of future and distant past conditional on present/recent past).
(1) What is the relationship between time non-homogeneity and non-linearity of a Markov chain?
(2) If time non-homogeneity and non-linearity are identical, please provide an intuitive, real world, example of such a Markov Chain process. If they are different types of Markov chains, please provide an intuitive, real world example of each.

A: your current state can be expressed probabilistically $$S_i=\{Pr(X=1)=p_1,Pr(X=2)=p_2,...,Pr(X=n)=p_n\}^T$$
all the previous states in theory could affect the current state
$$S_i=f_i(S_{i-1},S_{i-2},...,S_{0})$$
time homogeneity means f is always the same
$$f_i \equiv f$$
linearity means the function $f()$ can be expressed as a linear transform, i.e. multiplying a matrix, which in the order 1 and homogeneous case is $$S_i=Q \cdot S_{i-1}$$
but may also be non-homogenous $$ S_i=Q_i \cdot S_{i-1}, \space S_{i-1}=Q_{i-1} \cdot S_{i-2} ...$$
These 2 things are different.


text:
Q: Dynamically allocating a sum of 2d arrays in C For this exercise (where we must scan a txt file and return rows, columns, matrix 1 and matrix 2; then find the sum of matrix 1 and 2) there is extra credit for "using dynamic memory allocation," which is a few chapters ahead. Given my program below, how would I go about doing this? I know the 4 functions of dynamic memory allocation (malloc, calloc, free, and realloc), but not yet how to utilize them.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
    FILE *inFile;
    int i,j;
    int rows, cols;

    inFile = fopen ("Matrix.txt", "r");

    if (inFile == NULL)
    {
        printf("\n\nFile does not exist or cannot be opened.\n");
        exit(1);
    }
    fscanf(inFile,"%d %d", &rows, &cols);

    int m1[rows][cols],m2[rows][cols],m3[rows][cols];

    /*Scan and store Matrix 1 and Matrix 2*/
    for (i = 0; i < rows; i++)
    {
        for ( j = 0;j<cols;j++)
        {
            fscanf(inFile,"%d", &m1[i][j]);
        }
    }
    for (i = 0; i < rows; i++)
    {
        for ( j = 0;j<cols;j++)
        {
            fscanf(inFile,"%d", &m2[i][j]);
        }
    }

    fclose(inFile);

    printf("\nThe sum of the two matrices:\n");
    for (i = 0; i < rows; i++)
    {
        for (j = 0; j < cols; j++)
        {
            m3[i][j]=m1[i][j]+m2[i][j];
            printf("    %d", m3[i][j]);
        }
        printf("\n");
    }

}

A: I don't have your "Matrix.txt" file so I couldn't debug the code I wrote, but here it is anyway.
There's two answers bundled into one. The lazy way and the 2D array way.
I tend to prefer to handle my 2D arrays as 1D arrays in most cases since it's less code and fewer things to keep track of.
In order to test it, just comment or uncomment the #define.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define IF_LAZY (1) // comment/uncomment this line if you like lazy solutions or not.

int main() {
    FILE *inFile;
    int i, j;
    int rows, cols;

    inFile = fopen("Matrix.txt", "r");

    if (inFile == NULL) {
        printf("\n\nFile does not exist or cannot be opened.\n");
        exit(1);
    }
    fscanf(inFile, "%d %d", &rows, &cols);

#ifdef IF_LAZY

    /* Dynamic allocation using 1D arrays. */
    int* m1 = (int*) malloc(sizeof(int) * rows * cols);
    int* m2 = (int*) malloc(sizeof(int) * rows * cols);
    int* m3 = (int*) malloc(sizeof(int) * rows * cols);

#else

    /* Dynamic allocation using 2D arrays made out of pointers to pointers. */
    int** m1 = (int**) malloc(sizeof(int*) * rows);
    for(int i = 0; i < rows; i++) {
        m1[i] = (int*) malloc(sizeof(int) * cols);
    }

    int** m2 = (int**) malloc(sizeof(int*) * rows);
    for(int i = 0; i < rows; i++) {
        m2[i] = (int*) malloc(sizeof(int) * cols);
    }

    int** m3 = (int**) malloc(sizeof(int*) * rows);
    for(int i = 0; i < rows; i++) {
        m3[i] = (int*) malloc(sizeof(int) * cols);
    }

#endif

#ifdef IF_LAZY

    /*Scan and store Matrix 1 and Matrix 2*/
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            fscanf(inFile, "%d", &m1[i * cols + j]);
        }
    }
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            fscanf(inFile, "%d", &m2[i * cols + j]);
        }
    }

    fclose(inFile);

    printf("\nThe sum of the two matrices:\n");
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            m3[i * cols + j] = m1[i * cols + j] + m2[i * cols + j];
            printf("    %d", m3[i * cols + j]);
        }
        printf("\n");
    }

#else
    /*Scan and store Matrix 1 and Matrix 2*/
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            fscanf(inFile, "%d", &m1[i][j]);
        }
    }
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            fscanf(inFile, "%d", &m2[i][j]);
        }
    }

    fclose(inFile);

    printf("\nThe sum of the two matrices:\n");
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
            m3[i][j] = m1[i][j] + m2[i][j];
            printf("    %d", m3[i][j]);
        }
        printf("\n");
    }
#endif

}


text:
Q: Normal Form Theorem for Skew Symmetric Forms This is a theorem mentioned in Hansjorg Geiges' Symplectic Geometry book while proving Darboux's theorem for local realisation of a contact form on a manifold $M^{2n+1}$ (see $\S2.5.1$ p.67) I haven't seen this theorem in any textbook or on the net. Could anyone state it for me?

A: Perhaps it's referring to the result that for any nonsingular skew-symmetric form on a finite-dimensional vector space $V$ over any field, there is a basis $e_1, ..., e_n, f_1, ..., f_n$ of $V$ such that $\langle e_i, f_i \rangle = 1$, $\langle f_i, e_i \rangle = -1$, and all other pairings between basis vectors are 0.


text:
Q: Is it possible to exclude all css styling for one specific div container? I'm having problems using font-face on my website. I can get it working when testing it on a html file with it's own styling, but not if I include other style sheets.
I've tried overriding stles, placing style sheets in different order and so on, but nothing works.
So I'm wondering, is it possible to exclude all CSS and only use css from one css file for a specific div container?
(Without using iframe)

A: Unfortunately no, it's not possible to just clear or reset the styles for a specific container from the css it's inherited. You have to override each style that you want manually.
What you can do is you could namespace your classes and all you'd have to worry about would be element styles that you could define with defaults at the beginning of your style sheet. For example, something like:
div,table,span,img,p{
    margin: 0;
    padding: 0;
    border: 0;
    font-weight: normal;
    font-style: normal;
    font-size: 100%;
    line-height: 1;
    font-family: inherit;
    text-align: left;
}

You can of course add !important to ones that you need and add more elements to the list. If you can't trust or don't know the other styles that are going to be loaded and applied to your page, I find it's best to just start with an empty slate.

A: No, you cannot. There is no such exclusion mechanism in CSS or in HTML.
You real problem is probably solvable, though, but you did not describe it. You should describe, in a new question, what you want, what you have tried, and how it fails. With real code and/or URL.


text:
Q: How to filter on-click in react three js? So I explore 2 cubes sample. I want to click only on one cube at a time. Yet when I click on a cube that has a cube right behind the current one both get clicked. How to force click and hover only on the nearest one?
In other words clicking\hovering on cube A I want cube B not to be clicked

My code sample:
import React, { useRef, useState } from 'react'
import { Canvas, useFrame } from '@react-three/fiber'

function Box(props) {
  // This reference will give us direct access to the mesh
  const mesh = useRef()
  // Set up state for the hovered and active state
  const [hovered, setHover] = useState(false)
  const [active, setActive] = useState(false)
  // Rotate mesh every frame, this is outside of React without overhead
  useFrame(() => {
    mesh.current.rotation.x = mesh.current.rotation.y += 0.01
  })
  return (
    <mesh
      {...props}
      ref={mesh}
      scale={active ? 1.5 : 1}
      onClick={(e) => setActive(!active)}
      onPointerOver={(e) => setHover(true)}
      onPointerOut={(e) => setHover(false)}>
      <boxGeometry args={[1, 1, 1]} />
      <meshStandardMaterial color={hovered ? 'hotpink' : 'orange'} />
    </mesh>
  )
}

export default function App() {
  return (
    <Canvas>
      <ambientLight intensity={0.5} />
      <spotLight position={[10, 10, 10]} angle={0.15} penumbra={1} />
      <pointLight position={[-10, -10, -10]} />
      <Box position={[1.2, 0.5, 0]} />
      <Box position={[1.2, 0, 0]} />
    </Canvas>
  )
}

A: Solved it here
main diff:
function intersectionsFilter(intersections) {
  return intersections?.length ? [intersections[0]] : intersections
}

export default function App() {
  return (
    <Canvas raycaster={{ filter: intersectionsFilter }}>


text:
Q: Change Color of UI Table View's Specific row I want to change color dynamically if any new row is added to UITableView.If any row is selected Once than change color of that row. How Can I accomplish this task..?

A: You Can do like this,
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //First you get the cell you want to change
    UITableViewCell* theCell = [tableView cellForRowAtIndexPath:indexPath];

    //Then you change the properties (label, text, color etc..) in your case, the background color
    theCell.contentView.backgroundColor=[UIColor redColor];

    //Deselect the cell so you can see the color change

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}

A: You'll have reload the UITableView every time you need to change the color of your row. In your cellForRowAtIndexPath function you'll have setup a switch case:
switch(indexpath.row)
{
    case 1:
          //set the cell background color.
    .
    .
    .
    default :
          // color u want by default
}

If you want to change the color of particular row which is selected by user. Then you'll have to save the row number in didSelectRowAtIndexPath delegate method. And in cellForRowAtIndexPath change the background color of that particular row.
if(indexpath.row == selectedRow)
{
   //set this color
}
else
{
   //set another color
}


text:
Q: MySQL integer comparison ignores trailing alpha characters So lets just say I have a table with just an ID is an int. I have discovered that running:
SELECT *
FROM table
WHERE ID = '32anystring';

Returns the row where id = 32. Clearly 32 != '32anystring'.
This seems very strange. Why does it do this? Can it be turned off? What is the best workaround?

A: It is common behavior in most programming languages to interpret leading numerals as a number when converting a string to a number.
There are a couple of ways to handle this:
Use prepared statements, and define the placeholder where you are putting the value to be of a numeric type.  This will prevent strings from being put in there at all.
Check at a higher layer of the application to validate input and make sure it is numeric.
Use the BINARY keyword in mysql (I'm just guessing that this would work, have never actually tried it as I've always just implemented a proper validation system before running a query) -
SELECT *
FROM table
WHERE BINARY ID = '32anystring';

A: You need to read this
http://dev.mysql.com/doc/refman/5.1/en/type-conversion.html

*

*When you work on, or compare two different types, one of them will be converted to the other.

*MySQL conversion of string->number (you can do '1.23def' * 2 => 2.46) parses as much as possible of the string as long as it is still a valid number. Where the first letter cannot be part of a number, the result becomes 0


text:
Q: Referencing DOM nodes in Angular expressions is disallowed I started to work with directives and everything went well so far. But right now I'm stuck. I get an error Error: [$parse:isecdom] Referencing DOM nodes in Angular expressions is disallowed! Expression: report.getContent() and I don't see what kind of DOM node I'm referencing. Maybe I'm just dump!?
I've a scope function with will get a report instance:
$scope.showReport = function() {
            reportFactory.getLatestReport().then(function(report) {
                $scope.report = report;
            });
        };

My report object:
// report.js
return function(data) {
    return {
        content: new Content(data['content']),

        getContent: function() {
            return content;
        }
    }
};

The template which is in place will then call (?) a directive:

  <my-report></my-report>

myReport directive:
.directive('myReport', function() {
        return {
            templateUrl: 'report/report'
        };
    })

The returned template contains a directive as well:
<my-report-content content="report.getContent()"></my-report-content>

MyReportContent directive:
.directive('myReportContent', function() {
        return {
            templateUrl: 'report/content',
            scope: {
                content: '='
            }
        };
    })

Report template (report/content), but not working correctly since the error is thrown:

A: Wrong:
// report.js
return function(data) {
  return {
      content: new Content(data['content']),

    getContent: function() {
      return content;
    }
  }
};

Right:
// report.js
return function(data) {
  return {
      content: new Content(data['content']),

    getContent: function() {
      return this.content;
    }
  }
};


text:
Q: Test if a value is in a csv file in bash I have a 3-4M lines csv file (my_csv.csv) with two columns as :
col1,col2
val11,val12
val21,val22
val31,val32
...

The csv contains only two columns with one comma per line. Col1 and Col2 values are only strings (nothing else). The result shown above is the result of the command head my_csv.cs..
I would like to check if a string test_str is into the col2 values. What I mean here is, if test_str = val12  I would like the test to return True because val12 is located in column 2 (as show in the example).
But if test_str = val1244  I want the code to return False.
In python it would be something as :
import pandas as pd
df = pd.read_csv('my_csv.csv')
test_str = 'val42'

if test_str in df['col2'].to_list():
    # Expected to return true
    # Do the job

But I have no clues how to do it in bash.
(I know that df['col2'].to_list() is not a good idea, but I didn't want to use built-in pandas function for the code to be easier to understand)

A: awk is most suited amongst the bash utilities to handle csv data:
awk -F, -v val='val22' '$2 == val {print "found a match:", $0}' file

found a match: val21,val22

An equivalent bash loop would be like this:
while IFS=',' read -ra arr; do
   if [[ ${arr[1]} == 'val22' ]]; then
      echo "found a match: ${arr[@]}"
   fi
done < file

But do keep in mind that Bash while read loop extremely slow compared to cat, why?

A: Parsing CSV is difficult... unless your fields do not contain commas, newlines... And you don't do what you want in bash, on a large file it will be extremely slow. You do it using utilities like awk or grep that would also be available with dash, zsh or another shell. So, if you have a very simple CSV format you can use, e.g., grep:
if grep -q ',val42$' my_csv.csv; then
  <do that>
fi

We can also put the string to search for in a variable but remember that some characters have a special meaning in regular expressions and shall be escaped. Example if there are no special characters in the string to search for:
test_str="val42"
if grep -q ",$test_str$" my_csv.csv; then
  <do that>
fi

A: 3-4M rows is a small file to awk. might as well just do
{m,g}awk 'END { exit !index($_,","(__)"\n") }' RS='^$' FS='^$' __="${test_str}"


text:
Q: How can I transform some xml into a fixed length string using element attributes to define the value lengths <?xml version="1.0" encoding="UTF-8"?>
<Root>
    <Destination>acme.com</Destination>
    <Record>
       <FirstField length="10">AAAA</FirstField>
       <SecondField length="15">BBBB</SecondField>
       <SubRecord>
          <ThirdField length="20">CCCC</ThirdField>
          <FourthField length="8">DDDD</FourthField>
       </SubRecord>
    </Record>
</Root>

Hi, I have a requirement to take this xml example where the elements inside the  node will be dynamic & can be several layers deep, and create a fixed length string of text where each value is padded out to the left, using some xslt transformation that can process the xml until complete.   The length of each value is defined in the constant length attribute value   So the above example after transformation would be (inside the quotes so you can see the full length string:
"      AAAA           BBBB                CCCC    DDDD"

I've tried several attempts to create the required xslt to transform this, but haven't had much luck, as I don't know enough about xslt.
Is someone able to provide something that might work.   Needs to be in xsl 1.0.
Thanks.

A: Try this:
<xsl:variable name="spaces" select="'                                   '"/>
   <xsl:template match="/">
       <xsl:text>"</xsl:text>
       <xsl:for-each select="//*[@length]">
           <xsl:variable name="spacelenght" select="@length - string-length(.)"/>
           <xsl:value-of select="concat(substring($spaces, 1, $spacelenght), .)"/>
       </xsl:for-each>
       <xsl:text>"</xsl:text>
   </xsl:template>

Output
"      AAAA           BBBB                CCCC    DDDD"

See transformation at https://xsltfiddle.liberty-development.net/6q1S8AC
For your updated question
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="1.0">

    <xsl:output method="text"/>

    <xsl:variable name="spaces" select="'                                   '"/>

    <xsl:template match="/">
        <xsl:text>"</xsl:text>
            <xsl:apply-templates/>
        <xsl:text>"</xsl:text>
    </xsl:template>

    <xsl:template match="node()" priority="-1">
        <xsl:apply-templates/>
    </xsl:template>

    <xsl:template match="*[@Occurs]">
    <xsl:variable name="data">
        <xsl:apply-templates/>
    </xsl:variable>
    <xsl:call-template name="copy">
        <xsl:with-param name="data" select="$data"/>
        <xsl:with-param name="seq" select="0"/>
        <xsl:with-param name="lastseq" select="number(@Occurs)"/>
    </xsl:call-template>
</xsl:template>

<xsl:template name="copy">
    <xsl:param name="data"/>
    <xsl:param name="seq"/>
    <xsl:param name="lastseq"/>
    <xsl:copy-of select="$data"></xsl:copy-of>
    <xsl:if test="$seq < $lastseq">
        <xsl:call-template name="copy">
            <xsl:with-param name="data" select="$data"/>
            <xsl:with-param name="seq" select="$seq + 1"/>
            <xsl:with-param name="lastseq" select="$lastseq"/>
        </xsl:call-template>
    </xsl:if>
</xsl:template>

    <xsl:template match="*[@length]">
        <xsl:variable name="spacelenght" select="@length - string-length(.)"/>
        <xsl:value-of select="concat(substring($spaces, 1, $spacelenght), .)"/>
    </xsl:template>

</xsl:stylesheet>

Output
"      AAAA           BBBB                CCCC    DDDD                CCCC    DDDD                CCCC    DDDD                CCCC    DDDD                CCCC    DDDD                CCCC    DDDD                CCCC    DDDD                CCCC    DDDD                CCCC    DDDD                CCCC    DDDD"

See Transformation at https://xsltfiddle.liberty-development.net/6q1S8AC/2


text:
Q: Mapping Date and Time to MySQL I have created a table in MySQL as :
CREATE TABLE scheduled(sid INT,id INT,tweet VARCHAR(255),sdate DATE,
          stime TIME,PRIMARY KEY(sid),FOREIGN KEY(id) REFERENCES usercred(id));

I receive both Date and Time from the HTML input field. Date received from the HTML field looks like :
4/30/2014

How can I map this in Java ? After receiving both Date and Time and after mapping them correctly , I will commit the transaction or will update the table/entry.

A: In JDBC-layer inside PreparedStatement or ResultSet you work with the mapping java.sql.Date (for SQL-DATE) and java.sql.Time (for SQL-TIME). Then you can wrap both types like:
java.sql.Date sqlDate = ...; // from ResultSet
DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); // or M/d/yyyy
String htmlFormat = df.format(sqlDate);

And in reverse:
String htmlFormat = ...;
DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); // or M/d/yyyy
java.util.Date d = df.parse(htmlFormat);
java.sql.Date sqlDate = new java.sql.Date(d.getTime());
// use result in PreparedStatement for INSERT or UPDATE

Attention: Both approaches use the standard timezone of the server where this code is running. In case of doubt you should probably set the timezone UTC. Similar code for the TIME-part.

A: could use the parse() method in the SimpleDateFormat object:
SimpleDateFormat sdf = new SimpleDateFormat("M-dd-yyyy");
String dateInString = "4-30-1982"";
Date date = sdf.parse(dateInString);
System.out.println(date);


text:
Q: How to loop through a 2D list diagonally in python? If I have a function val) and then I also need to check there is the letter  in it
 iagonally)

A: If your 2D list is guaranteed to be square, then you can do the diagonal check as follows
def diagnoal_check(board2d, start_row, start_column, goal_row, goal_column, row_increment, column_increment):
    curr_row = start_row
    curr_column = start_column
    while(curr_column < len(board2d) and curr_row < len(board2d) and curr_row >= 0 and curr_column >= 0):
        if(board2d[curr_row][curr_column] == "P"):
            return False
        if(curr_column == goal_column and curr_row == goal_row):
            return True

        curr_column += column_increment
        curr_row += row_increment
    return False

and then update your conditional code as follows
x = False
if (abs(currow - newrow) == abs(curcol - newcol)):
    x = True
    if ((curcol < newcol) and (currow > newrow)): #NorthEast
        x = diagnoal_check(board2d, currcol, currow, newcol, newrow, -1, 1)
    elif ((curcol < newcol) and (currow < newrow)): #SouthEast
        x = diagnoal_check(board2d, currcol, currow, newcol, newrow, 1, 1)
    elif ((curcol > newcol) and (currow < newrow)): #SouthWest
        x = diagnoal_check(board2d, currcol, currow, newcol, newrow, 1, -1)
    elif ((curcol > newcol) and (currow > newrow)): #NorthWest
        x = diagnoal_check(board2d, currcol, currow, newcol, newrow, -1, -1)

else:
    x = False
    return x

For your question in the title, looping through a list diagonally isn't that complicated, it's just your use case that made it a bit harder, but in general it could be achieved by :
for i in range(len(your_2d_list)):
   print(your_2d_list[i][i])

A: This approach doesn't need to know the direction thanks to the range(start,stop,step) function, bound in a list comprehension

def validate_move(matrix, cur_row, cur_col, new_row, new_col):
    x = False
    if abs(cur_row - new_row) == abs(cur_col - new_col):
        # Create a mapping of points to analyse
        crossed_points = [
            [x for x in range(cur_row, new_row, 1 if new_row - cur_row >= 0 else -1)],  # list of rows indexes
            [y for y in range(cur_col, new_col, 1 if new_col - cur_col >= 0 else -1)],  # list of columns indexes
        ]
        # Check each crossed point to see if P is present
        for point in range(len(crossed_points[0])):
            if matrix[crossed_points[0][point]][crossed_points[1][point]] == "P":
                x = True
                # Stop the loop because P is found
                break
    else:
        x = False
    return x


text:
Q: jQuery Center Div toggle in IE6 Click the button to center div, click again to left align. This works in all browsers except IE6. IE6 doesn't support margin:0 auto; How can i work around this. div width is dynamic and not always 200px.
Check jsfiddle http://jsfiddle.net/hZ23J/1/
<button id="center">Left Align</button>

$('#center').toggle(function() {
    $('div').css('margin', '0');
    $(this).text('Center Align')
}, function() {
    $('div').css('margin', '0 auto');
    $(this).text('Left Align')
});

A: For IE6 use
body{
text-align:center;
}

And your jQuery code will look like
$('#center').toggle(function() {
    $('div').css('margin', '0');
    $('body').css('text-align', 'left');
    $(this).text('Center Align')
}, function() {
    $('div').css('margin', '0 auto');
    $('body').css('text-align', 'center');
    $(this).text('Left Align')
});

Check working example at http://jsfiddle.net/jNWYP/1/

A: This solution works for me in IE6...
$('#center').click(function () {
    $('div').toggleClass('center');
});

class...
.center { margin: 0px auto; }

It's also good practice to keep your JS and CSS separate when possible.
Here is my doctype...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


text:
Q: Forward HTTP (or TCP) request through NGINX using subdomain to a specific port I want to expose a local web server through a remote webs server. The remote host has already an Nginx and a web application (webmail). The remote server works as a gateway for the local webserver who's forwarding the port 80 to the remote 8080. This is working.
Now I want to forward the subdomain (e.g., bridge.mydomain.co) requests to the forwarded port. I tried using this:
server {
    listen 80;
    listen [::]:80;
    server_name bridge.mydomain.co;

    location / {
        proxy_set_header Host $host;
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

The local webserver is running a complex PHP application so it is complaining:
40 errors like:

Refused to load the stylesheet '' because it violates the
following Content Security Policy directive: "default-src https: data:
'unsafe-inline' 'unsafe-eval'". Note that 'style-src-elem' was not
explicitly set, so 'default-src' is used as a fallback.

and 56 of:

Refused to load the script '' because it violates the following
Content Security Policy directive: "default-src https: data:
'unsafe-inline' 'unsafe-eval'". Note that 'script-src-elem' was not
explicitly set, so 'default-src' is used as a fallback.

I know I could expose the forwarded port directly, this works flawlessly. But I want to use (eventually) nginx for TLS termination and then forwarding.
Reading about this issue seems that the local webserver in PHP is refusing the requests. Yet, I don't know how to fix it.
Any help?

A: Figure it out at the end. I needed to pass/add the following headers:
server {
    listen 80;
    listen [::]:80;
    server_name bridge.mydomain.co;

    proxy_pass_header server;

    location / {
        proxy_set_header Host $host;
    add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' http://bridge.mydomain.co http://bridge.mydomain.co:8080  http://bridge.mydomain.co/core/img/favicon-touch.png; img-src 'self' http://bridge.mydomain.co http://bridge.mydomain.co:8080;";
        proxy_pass http://bridge.mydomain.co:8080;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

}

I believe the port version is not needed and there are some headers missing that are covered by the "default". So there is room for improvement.
If you want to read an explanation here there is some material from people more knowledgeable than me: https://stackoverflow.com/questions/33300111/how-to-override-content-security-policy-of-site-a-while-using-nginx-proxy-pass-o


text:
Q: HttpPost to web api is always a null parater I'm trying to post some data to a web api app from an angular 2 app. Its only a small json string and when I hit the web api controller, the item is always null - no matter what I've tried.
The json is  (I can see this from alerting the data)
{"firstname":"Joe","lastname":"Bloggs"}

The angular function is
    createUser(user: Profile): Observable<Response> {

    let url = this.usersUrl;
    let data = JSON.stringify(user);
    let headers = new Headers({'Content-Type': 'application/json; charset=utf-8' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(url, data, options);
}

The web api conroller method is:
    [HttpPost]
    public IActionResult Create(User item)
    {
        if (item == null)
        {
            return BadRequest();
        }
        Users.Add(item);
        return CreatedAtRoute("GetUser", new { id = item.Id }, item);
    }

but when I break point at Create the User item is null.
I've tried :
   public IActionResult Create([FromBody] User item)

but the error message in the Chrome console window is
Failed to load resource: the server responded with a status of 415 (Unsupported Media Type)

I've tried
    let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' });

but the error is the same as above.
Any ideas?:)

A: I imagine that your problem is your user model in API. The properties need to be exactly equals.


text:
Q: Error deserializing JSON file in Visual Studio I am having a difficulty trying to extract data from the following JSON table:
    [
    {"type":"header","version":"4.8.3","comment":"Export to JSON plugin for PHPMyAdmin"},
    {"type":"database","name":"archaism_dictionary"},
    {"type":"table","name":"dictionary","database":"archaism_dictionary","data":
    [
    {"id":"0","word":"wordOne","synonym":null,"definition":"defOne"},
    {"id":"1","word":"wortTwo","synonym":null,"definition":"defTwo"}
    ]
    }
    ]

My goal is to get a string output for each "word" and each "definition". I have the following class which corresponds to the JSON file:
public class Rootobject
{
    public Class1[] Property1 { get; set; }
}

public class Class1
{
    public string type { get; set; }
    public string version { get; set; }
    public string comment { get; set; }
    public string name { get; set; }
    public string database { get; set; }
    public Datum[] data { get; set; }
}

public class Datum
{
    public string id { get; set; }
    public string word { get; set; }
    public object synonym { get; set; }
    public string definition { get; set; }
}

Finally this piece of code is supposed to retrieve the first word from the table in the string result:
var list = JsonConvert.DeserializeObject<List<Dictionary.Rootobject>>(rawJSON);
string result = list[0].Property1[0].data[0].word;

The .Property[0] returns null and the program gives me a null reference exception. Where is my code faulty and how should I accomplish this task? Thank you.
EDIT:
I am not sure whether this can mess up the rawJSON string but I get it like this:
rawJSON = File.ReadAllText(FileSystem.AppDataDirectory + fileName);

A: It is more likely that your input json is something like this:
[
{"type":"header","version":"4.8.3","comment":"Export to JSON plugin for PHPMyAdmin"},
{"type":"database","name":"archaism_dictionary"},
{"type":"table","name":"dictionary","database":"archaism_dictionary","data":
[
{"id":"0","word":"wordOne","synonym":null,"definition":"defOne"},
{"id":"1","word":"wortTwo","synonym":null,"definition":"defTwo"}
]

Note square brakets, they're important.
If I guessed it right, you'll want to deserialize like this:
var list = JsonConvert.DeserializeObject<List<Class1>>(rawJSON);
string result = list[2].data[0].word;

Note: your original code would work only if your input json were:
{
  "Property1":[
    {"type":"header","version":"4.8.3","comment":"Export to JSON plugin for PHPMyAdmin"},
    {"type":"database","name":"archaism_dictionary"},
    {"type":"table","name":"dictionary","database":"archaism_dictionary","data":
      [
        {"id":"0","word":"wordOne","synonym":null,"definition":"defOne"},
        {"id":"1","word":"wortTwo","synonym":null,"definition":"defTwo"}
      ]
    }
  ]
}

and use
var myRoot = JsonConvert.DeserializeObject<RootObject>(rawJSON);
string result = myRoot.Property1[2].data[0].word;

A: @ Claudio Valerio provide the right json data.
Based on my test, you could try the code below to get the word in the list.
Json daya:
{
"Property1":[
{"type":"header","version":"4.8.3","comment":"Export to JSON plugin for PHPMyAdmin"},
{"type":"database","name":"archaism_dictionary"},
{"type":"table","name":"dictionary","database":"archaism_dictionary","data":
  [
    {"id":"0","word":"wordOne","synonym":null,"definition":"defOne"},
    {"id":"1","word":"wortTwo","synonym":null,"definition":"defTwo"}
  ]
  }
 ]
}

Class from JSON data:
 public class Rootobject
{
    public Property1[] Property1 { get; set; }
}

public class Property1
{
    public string type { get; set; }
    public string version { get; set; }
    public string comment { get; set; }
    public string name { get; set; }
    public string database { get; set; }
    public Datum[] data { get; set; }
}

public class Datum
{
    public string id { get; set; }
    public string word { get; set; }
    public object synonym { get; set; }
    public string definition { get; set; }
}

Code:
  string rawJSON = @"{
  'Property1':[
    {'type':'header','version':'4.8.3','comment':'Export to JSON plugin for PHPMyAdmin'},
   {'type':'database','name':'archaism_dictionary'},
   {'type':'table','name':'dictionary','database':'archaism_dictionary','data':
   [
    {'id':'0','word':'wordOne','synonym':null,'definition':'defOne'},
     {'id':'1','word':'wortTwo','synonym':null,'definition':'defTwo'}
  ]
  }
 ]
}";
        var list = JsonConvert.DeserializeObject<Rootobject>(rawJSON);
        string result = list.Property1[2].data[0].word;

A: You need to null handle(json NullValueHandling) below is my code please take a look :
string stringJson = @"{
                              'Property1':[
                                {'type':'header','version':'4.8.3','comment':'Export to JSON plugin for PHPMyAdmin'},
                               {'type':'database','name':'archaism_dictionary'},
                               {'type':'table','name':'dictionary','database':'archaism_dictionary','data':
                               [
                                {'id':'0','word':'wordOne','synonym':null,'definition':'defOne'},
                                 {'id':'1','word':'wortTwo','synonym':null,'definition':'defTwo'}
                              ]
                              }
                             ]
                            }";

        try
        {
            var settings = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
                MissingMemberHandling = MissingMemberHandling.Ignore
            };
            var list = JsonConvert.DeserializeObject<BaseResponse>(stringJson,settings);
            string result = list.Property1[2].data[0].word;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

Models :
public class WordData
{
    public string id { get; set; }
    public string word { get; set; }
    public object synonym { get; set; }
    public string definition { get; set; }
}

public class PropertyData
{
    public string type { get; set; }
    public string version { get; set; }
    public string comment { get; set; }
    public string name { get; set; }
    public string database { get; set; }
    public List<WordData> data { get; set; }
}

public class BaseResponse
{
    public List<PropertyData> Property1 { get; set; }
}

I hope it will help you
Thanks


text:
Q: Python create list from smallest number of repeating values in a nested list I have a Dict
whs = {
    'ID1' : ['code1', 'code2', 'code3'],
    'ID2' : ['code2', 'code5', 'code3'],
    'ID3' : ['code6', 'code7', 'code8'],
    'ID4' : ['code3', 'code5', 'code6'],
}

What I need to do is build a new list that will look like
submit = [
    {
        'codes' : ['code3', ],
        'ids' : ['ID1', 'ID2', 'ID4'],
    },
    {
        'codes' : ['code6', 'code7', 'code8'],
        'ids' : ['ID3', ],
    }
]

What I have so far
def ParseAvailable(self, whs):
    separate = whs.keys()
    submit = []
    while len(separate) > 0:
        avail = {
            'codes' : [],
            'ids' : [],
        }
        for num, item in enumerate(separate):
            if len(avail['codes']) == 0:
                avail['codes'] = whs[item]
                avail['ids'].append(item)
            else:
                avail_all = list(set(avail['codes']) & set(whs[item]))
                print '%s : %s' % (item, avail_all)
                if len(avail_all) > 0:
                    avail['codes'] = avail_all
                    avail['ids'].append(item)
            if len(avail['codes']) > 0:
                del separate[num]
        submit.append(avail)
    return submit

Which returns:
[
    {
        'ids': ['ID4', 'ID3'],
        'codes': ['code6']
    },
    {
        'ids': ['ID2'],
        'codes': ['code2', 'code5', 'code3']
    },
    {
        'ids': ['ID1'],
         'codes': ['code1', 'code2', 'code3']
    }
]

which COULD work except that ID1 & ID2 should be combined as
{
    'ids' : ['ID1', 'ID2',],
    'codes' : ['code2', 'code3', ]
}

Curious if there is an easier approach that I've not thought of, figure I could setup a couple more nested loops to compare everything piece by piece though it seems rather unpythonic
Thank You in Advance

A: I attacked it by building a tree of all the potential additions, and then finding the cheapest option among those.  Here is a working (albeit ugly and unoptimized) example:
https://gist.github.com/1288835
The tree will end up with p*w nodes, where p is the number of products and w(p) is the average number of warehouses per product.

A: So it looks to me like you have a set cover problem, which is NP-complete. Not only that, but it appears that you want all the possible set covers of the minimum size. Your list of ids creates the universe set, and each of your codes creates a sub set of the universe.
For your simple iterative loops you don't really have a choice other then to try all possible combinations of codes. If you have large data sets this isn't going to work.
The wikipedia article mentions an efficient algorithm (greedy algorithm) that isn't guaranteed to find the best solution, but the error in the solution is bounded. This algorithm is to iteratively add the subset the contains the most uncovered elements of the universe.
If you need to get the absolutely correct answer you may want to try the Integer Programming approach (as in Linear Programming). There are software packages and libraries for this algorithm.

A: As others said, this is an optimization problem that isn't trivial for large datasets.  But as a first step, it's at least easy to invert the list of warehouses per product to a list of products per warehouse.
whs = {
    'ID1' : ['code1', 'code2', 'code3'],
    'ID2' : ['code2', 'code5', 'code3'],
    'ID3' : ['code6', 'code7', 'code8'],
    'ID4' : ['code3', 'code5', 'code6'],
}

a = []
b = []
for k,v in whs.items():
    for j in v:
        a.append((j,k))
        b.append((j,[]))
inv = dict(b)
for j in a:
    inv[j[0]].append(j[1])

print("Inventory:")
for k,v in inv.items():
    print(k,v)

When run, this prints:
Inventory:
code1 ['ID1']
code2 ['ID2', 'ID1']
code3 ['ID4', 'ID2', 'ID1']
code5 ['ID4', 'ID2']
code6 ['ID4', 'ID3']
code7 ['ID3']
code8 ['ID3']

As you can see from the trivial example, there are no solutions that will get all products in a single order, and several solutions (code2+code6, code3+code6, code3+code7, code3+code8) that will get them in two orders.  Picking the "best" would require additional information, such as pricing, to optimize on.


text:
Q: How to observe the Add action of DbSet? I has two classes named Contact and ContactField as following. When the ContactField is added into Contact, I hope to assign SortOrder to ContactField automatically. Do I need to inherit DbSet and customize the Add method ? How to achieve it ?
public class Foo {
        private MyDbContext _db = new MyDbContext();

        public void HelloWorld() {
            Contact contact = ....; //< A contact from database.

            ContactField field = ....; ///< A new field
            .... ///< assign other properties into this `field`
            field.FieldType = FieldType.Phone;

            // How to automatically update `SortOrder`
            // when adding field into `ContactFields`
            contact.ContactFields.Add(field);

            _db.SaveChanges();
        }
}

public class Contact {
        public long ContactID { get; set; }

        public string DisplayName { get; set; }
        public string DisplayCompany { get; set; }
        public DateTime CreatedTime { get; set; }
        public DateTime ModifiedTime { get; set; }

        // Original codes
        //public virtual ICollection<ContactField> ContactFields { get; set; }
        public virtual MyList<ContactField> ContactFields { get; set; }
}

 public class ContactField {
        public long ContactFieldID { get; set; }
        public int SortOrder { get; set; }
        public int FieldType { get; set; }

        public string Value { get; set; }
        public string Label { get; set; }

        [Column("ContactID")]
        public int ContactID { get; set; }
        public virtual Contact Contact { get; set; }
 }

Edit:
    I found what I need is to monitor the changes of ICollection<ContactField> ContactFields. And the List<T> is an implementation of ICollection<T>. So, I create a custom MyList and ask it notifies the changes of MyList container. I will test it works or not later.
public class MyList<TEntity> : List<TEntity> {
        public delegate OnAddHandler(object sender, TEntity entry);
        public event OnAddHandler OnAddEvent;

        public new void Add(TEntity entity) {
             OnAddEvent(this, entity);
             base.Add(entity);
        }
 }

A: The DbSet has a Local property which is an ObservableCollection. You can subscribe to the CollectionChanged event and update the sort order there.
public class Foo {
        private MyDbContext _db = new MyDbContext();

        public void HelloWorld() {

            _db.Contacts.Local.CollectionChanged += ContactsChanged;

            Contact contact = ....; //< A contact from database.

            ContactField field = ....; ///< A new field
            .... ///< assign other properties into this `field`
            field.FieldType = FieldType.Phone;

            // How to automatically update `SortOrder`
            // when adding field into `ContactFields`
            contact.ContactFields.Add(field);

            _db.SaveChanges();
        }

        public void ContactsChanged(object sender, NotifyCollectionChangedEventArgs args) {

            if (args.Action == NotifyCollectionChangedAction.Add)
            {

                // sort
            }
        }
}

A: Alternatively override the SaveChanges method on the DbContext, and use the local ChangeTracker property to find new entities of a particular type and set their sort order property.  Works great for setting things like last updated date in 1 place.


text:
Q: How to return a reference to a field in an Iterator? I need to save a reference to a field of an Iterator in the struct which is returned by the next-method. However the compiler cannot infer an appropriate lifetime for the borrow expression.
Is this possible in the current release of Rust an how can I do it?
In the following is a reduced code snippet and the full error message:
use std::collections::HashMap;

struct CellDataRef<'a> {
    value: &'a str,
}

struct Row<'a> {
    data_ref: &'a HashMap<String, CellDataRef<'a>>,
}

struct TableIterator<'a> {
    data: HashMap<String, CellDataRef<'a>>,
}

impl<'a> Iterator for TableIterator<'a> {
    type Item = Row<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        Some(Row {
            data_ref: &self.data,
        })
    }
}

Compiler error:
error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
  --> src/lib.rs:20:23
   |
20 |             data_ref: &self.data,
   |                       ^^^^^^^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 18:5...
  --> src/lib.rs:18:5
   |
18 |     fn next(&mut self) -> Option<Self::Item> {
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...so that reference does not outlive borrowed content
  --> src/lib.rs:20:23
   |
20 |             data_ref: &self.data,
   |                       ^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined on the impl at 15:6...
  --> src/lib.rs:15:6
   |
15 | impl<'a> Iterator for TableIterator<'a> {
   |      ^^
note: ...so that the types are compatible
  --> src/lib.rs:18:46
   |
18 |       fn next(&mut self) -> Option<Self::Item> {
   |  ______________________________________________^
19 | |         Some(Row {
20 | |             data_ref: &self.data,
21 | |         })
22 | |     }
   | |_____^
   = note: expected `Iterator`
              found `Iterator`


text:
Q: Extract uintptr from reflect.Value Given
// I know that behind SomeInterface can hide either int or a pointer to struct
// In the real code I only have v, not i
i := something.(SomeInterface)
v := reflect.ValueOf(i)
var p uintptr
if "i is a pointer to struct" {
    p = ???
}

*

*I need some way to distinguish between pointers and values in this situation.

*If i was a pointer to struct, I need to cast it to uintptr.

Something I discovered so far: the second member of the (*reflect.Value).InterfaceData() will be the pointer to the struct, in case it is a struct. I have no idea what it is in case it is not a struct.

A: Use the Pointer method to get the address of a struct as a uintpr:
var p uintptr
if v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct {
    p = v.Pointer()
}

playground example
This code assumes that v is the result of calling reflect.ValueOf(i) as shown in the question.  In this scenario, v represents i's element, not i.  For example, if interface i contains an int, then v.Kind() is  reflect.Int, not reflect.Interface.
If v has an interface value, then drill down through the interface to get the uintptr:
if v.Kind() == reflect.Interface {
    v = v.Elem()
}
var p uintptr
if v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct {
    p = v.Pointer()
}

playground example


text:
Q: User friendly tool for internationalization in CakePHP 1.3 I have a multi language website written in CakePHP 1.3 and I'm currently in the process of adding a new language. I have the original .pot file and I generated a new .po file for the given language. So far so good, it's all working, however, now someone has to do the actual translation. I've send them the relevant .po file with explanations what to do but they seem to have problems dealing with plain text file. Is there a user friendly tool or piece of code that would actually allow them to translate the phrases one by one, without having to deal with text files?

A: You need a po editor. There are many out there for various platforms. Some free, some not. They usually provide a simple interface for viewing all the available translation strings and adding the translation next to them without need for viewing the po file in a text editor. My understanding is that many translators are familiar with this type of software so may already have one installed.
Check out this Stack Overflow question and answers for suggestions:-
What good alternatives to poEdit are there?


text:
Q: Should links contains the authentication token in HateOAS? I'm using Spring MVC and Spring HateOAS to make a restful and stateless JSON API.
Everything works fine. But i have a "conception" question. My API use an authentication token in every request. For example, you use the login API to get your authentication token, and when you call my API you must use it like this :
http://some_host/api/foo/bar?token=abcd

The API always respond a JSON and links are generated via Spring HateOAS. For exemple :
{
    "label" : "foo",
    "links" : [
        "rel" : "self",
        "href" : "http://some_host/api/foo/bar/1234656"
    ]
}

The question is : Should i add the authentication token in the generated URL ? (so it will be http://some_host/api/foo/bar/1234656?token=abcd)
I can't find any advice or convention for that.

A: Usually, authentication tokens are communicated via standard HTTP headers (such as the Authorization header in the case of HTTP Basic or Digest). The other common one is via a cookie. In Servlet environments, this is usually the JSESSIONID cookie.
Generally speaking, you shouldn't see authentication tokens passed as part of the request URL.

A: This is an old question, but the answer is definitely no.
http://some_host/api/foo/bar/1234656 is supposed to be the uniform identifier (URI) and location (URL) for that resource. It's the one URL you can rely on. You can always get the resource using that URL but you'll never get the resource with http://some_host/api/foo/bar?token=abcd again, because the token will expire.
Calling the URL with the token appended is one thing, but it should never appear in the link, because it has nothing to do with the resource. It's the client's responsibility to send the token, not the server's one.


text:
Q: How to extract 2-word fields from Object? I have the following JSON object:
{
"features": [{
    "properties": {
        "lat": "1.2345",
        "location c": "aaa",
        "location q": "cccc"
    }
    }
 ]
}

So I can fetch properties and what next?
As you see above mentioned fields have 2 words.
 var location_c =  properties.get(/*???*/);

How can I do that in JavaScript?

A: Use bracket syntax.
 var location_c = properties['location c'];


text:
Q: Custom function to quit processing asp.net request I´m come from old VB totaly new to C#. I want to build a helper function, that I can call in this way:
 void fError(400, "Parameter X is missing");

or
 void fError(500, "Unexpected Error occured");

This should be a "shortcut" for me: only one line to quit processing the page with my custom error messages and Standard http error codes.
This should be my "function":
    private void fError(int pErrorCode, string pErrorMessage)
    {
        var mCode;
        if (pErrorCode == 500)
        {
            mCode = HttpStatusCode.InternalServerError;
        }
        if (pErrorCode == 400)
        {
            mCode = HttpStatusCode.BadRequest;
        }
        throw new HttpResponseException(new HttpResponseMessage(mCode)
        {
            Content = new StringContent(pErrorMessage),
            ReasonPhrase = "MyApplication Error"
        });
    }

Any idea how to get this work?

A: you're almost there. your code seems to suggest you're using ASP.NET Web API.
let me know if now.
you can simplify your code further by using.
  private void fError(HttpStatusCode statusCode, string pErrorMessage)
    {
        throw new HttpResponseException(statusCode)
        {
            Content = new StringContent(pErrorMessage),
            ReasonPhrase = "MyApplication Error"
        });
    }

OR, if you don't want to send HttpStatusCode types (why not?) and want to send integers
  private void fError(int statusCode, string pErrorMessage)
    {
        throw new HttpResponseException((HttpStatusCode)statusCode)
        {
            Content = new StringContent(pErrorMessage),
            ReasonPhrase = "MyApplication Error"
        });
    }

A: Got it with the second solution:
    public static void fError(string pErrorMessage, int pStatusCode)
    {
        throw new HttpResponseException(new HttpResponseMessage
        {
            StatusCode = (HttpStatusCode)pStatusCode,
            Content = new StringContent(pErrorMessage),
            ReasonPhrase = "MyApplication Error"
        });
    }


text:
Q: How to set-up a Typescript class so my Browser AND Node app can use it? I have written a web app which is simply 2 separate projects with each in different folders and their own unique files.
The client portion is written in Angular 2 (RC-4) using SystemJS Typescript 1.8.10 (as per here).
The server portion is a simple NodeJS app using Typescript 1.8.10 (as well).
As mentioned each have their own folder and their own unique files (including their own tsconfig.json file.)
All is working fine.
But now, I want to use a class MySharedClass {} to be used in BOTH of these projects. How on earth do I do this?
Sure, I can put a source-code copy in each of the projects (i.e. have 2 copies of the source file), and it builds and runs fine - but that is NOT how we do things.
I thought of creating a 'third' project called 'common' and putting MySharedClass {} in there, but I can't do a
import {MyClass} from "../../../common/my-class";
in each of my projects because it doesn't seem to reference it when I run it. (I wasn't able to get it to reference the file during run-time as I believe the reason is that you can't reference the file outside the scope of the project ?!?)
Researching around, there does not seem to be an explanation on how to do this - am I missing something obvious?
Please feel free to point me in the right direction as to what people are doing to solve this - is there something I need to learn? I'm quite sure I understand the ES6 module system (as per the recent Typescript ES6 way) as I've been using this method in the projects. I'm not currently using a build tool as I don't require the additional complexity: I'm just using scripts provided in the package.json file (as per here). Should I need to look into using Gulp now?

A: Thanks. Yes @Zen it is a problem of the include path. I'm not using Visual Studio and using Node as the webserver (I was using Atom but it keeps hanging so its back to Notepad++ I go...). Yes @jobou you're right saying that the common dependencies are outside the folder and thus so not serviceable by the web server. I've solved my issue by (as @Zen says) by creating a third project called 'common' and when I build each of the other projects, I just run a simple script which copies the necessary files over to the appropriate folders so the other projects can use the class.


text:
Q: LED Cube with no transistors Regarding this instructable , why is it possible to build this circuit without transistors?
We have 4 layers of LEDs like that, which is controlled by an Arduino.

Every circle is a LED, the blue arrows are connections to ground (individual pins set to LOW on the arduino when the LED should turn on).
And there's 1 connection to a HIGH pin on each layer with a 100 Ohm resistor.
In total 16 Pins for the ground connections and 4 Pins for each layer (VCC).
This code turns all LEDs on 1 layer on.
////////////////////////////////////////////////////////////turn all on
void turnEverythingOn()
{
  for(int i = 0; i<16; i++)
  {
    digitalWrite(column[i], 0);
  }
  //turning on layers
  for(int i = 0; i<4; i++)
  {
    digitalWrite(layer[i], 1);
  }
}

So when everything is turned on, each layer pin has to drive 16 LEDs, this will result in a higher current load than what the atmega chip on the Arduino can supply. At least this was my original question / concern.
My original understanding was that there are 4 LEDs in series (one vertical red line connecting 4 LEDs) and that each of these 4 lines are in parallel.
As already has been pointed out in the answers / comments, the 16 LEDs are actually in parallel.
The calculation for the resistor was made via 2 V / 0.02 A = 100 Ohm.
Remaining questions:
1) I don't see why all 16 LEDs per layer are in parallel? Is it because they don't share a common ground connection but each one has an individual ground?
If I imagine the red vertical lines (only drew 2) look like this

simulate this circuit – Schematic created using CircuitLab
and you could also draw it like that

simulate this circuit
then I think I understand why all 16 LED are in parallel.
2-ish) The calculation for the 100 Ohm resistor results in:
2V is shared among all LEDs and they have to share the 20 mA provided by the current limiting resistor? This would match passerby's calculation of 1.25 mA per LED. I assume 20 mA was chosen to have enough headroom to the max. current?
The I can understand why we don't need transistors.

A: Each layer is tied into a single 100 ohm resistor. This limits the total current for the 16 leds in a layer to 20 mA total, in theory. As the internal resistance of the atmega pin also changes the available voltagr based on the current passed, the actual current may be slightly lower.
Since its limited to 20mA, the pin would not blow and there is no need for a transistor to allow a higher current carrying capacity. And each led can still be bright at 1.25 mA each in parallel.


text:
Q: Where does the integral come from in this Spring formula describing displacement at a certain point? I'm in the process of trying to combine some equations for a simulation.
One describes the position at a point along a hanging slinky using...
$$y(d) = (l_1 + {mg\over k})d - {mg\over 2k}d^2$$
(source: http://large.stanford.edu/courses/2007/ph210/kolkowitz1/)
where...

*

*$d$ is a point between [0-1] along the spring's mass.  ie .5 is the midway point, and the mass up until that point is total mass/2

*$l_1$ is the length of the slinky without any external force.  Since a slinky is a 'pretensioned' spring, at rest its coils are touching.  This is the 'minimum' length, and the slinky is displaced from here

*$mg\over k$ denotes the total spring displacement when hanging due to the force of gravity.  This is derived from Hooke's law and Newton's 2nd law

*$k$ is the spring constant

Part 1 I understand:
$$(l_1 + {mg\over k})d$$
This just means the (minimum length + displacement) * fraction of mass.  Since the mass is directly proportional to displacement, this should give us the displacement at point $d$ along the slinky spring
Part 2 I don't understand:
$$-{mg\over 2k}d^2$$
This is obviously (I think) the integral of ${mg\over k}d$.  But why?  ${mg\over k}d$ is not a rate, such as velocity, but it is a distance.  And why do we subtract it from Part 1?


text:
Q: Saving a temporary managed object context on a background queue According to the Concurrency with Core Data Guide, you should not save a NSManagedObjectContext in a background thread, because it is possible for the app to quit before the save completes, since threads are detached.
If I'm understanding correctly, that means something like this is incorrect
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
    NSManagedObjectContext* tempContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
    [tempContext setParentContext:[[MyDataManager sharedInstance] mainContext];
    [tempContext performBlockAndWait:^{
         //Do some processing
        NSError* error;
        [tempContext save:&error];
    }];
});

My first instinct would be to just save the context on the main queue when it's finished, but managedObjectContexts are supposed to be thread safe. Is the following something that would solve the problem or is there a better solution?
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
    NSManagedObjectContext* tempContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
    [tempContext setParentContext:[[MyDataManager sharedInstance] mainContext];
    [tempContext performBlockAndWait:^{
        //Do some processing
    }];
    dispatch_async(dispatch_get_main_queue(), ^{
        [tempContext performBlockAndWait:^{
            NSError* error;
            [tempContext save:&error];
        }];
    });
});

A: First:
In your first example:
The [context save:...] should be done in the context's performBlockAndWait: block.
Also, if you are using a background context, you could simply call its performBlock: method, as it is already use GCD for dispatching, so it will look something like:
NSManagedObjectContext* tempContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[tempContext setParentContext:[[MyDataManager sharedInstance] mainContext];
[tempContext performBlock:^{
    //Do some processing
    NSError* error;
    [tempContext save:&error];
}];

Secondly:
"Saving in a Background Thread is Error-prone" (as I know it and understand it) means:
You can save in the background, but it is NOT guaranteed that the save you called will run to completion if the application quit (the database would still be valid, or could be rolled back to a pre-partial-save state).
==>
If you use background save, don't assume that a save operation has completed between 2 application executions.
Thirdly (just to emphasise):
DON'T use a private-queue context without performBlock: or performBlockAndWait:
==>
Your second example will lead to unexpected behavior


text:
Q: React - How to check if JWT is valid before sending a post request? another noob question. I'm logging in my user to the system using JWT authorization, getting the token and saving it in localstorage and then sending a post request that saves data (its a big form basically). Problem is, the sever is invalidating the token after a given time (20 minutes or so) and so, some of my post requests are returning 401 status. How to verify (and if needed, show a login prompt) before sending the post request? I'm using redux-form to make my forms.
P.S: I know I'm supposed to use action creators and such, but I'm still a newbie, so not very good at those stuff.
here's my authentication:
export function loginUser(creds) {

const data = querystring.stringify({_username: creds.username, _password: creds.password});

let config = {
    method: 'POST',
    headers: { 'Content-Type':'application/x-www-form-urlencoded' },
    body: data
};

return dispatch => {
    // We dispatch requestLogin to kickoff the call to the API
    dispatch(requestLogin(creds));

    return fetch(BASE_URL+'/login_check', config)
        .then(response =>
            response.json().then(user => ({ user, response }))
        ).then(({ user, response }) =>  {
            if (!response.ok) {
                // If there was a problem, we want to
                // dispatch the error condition
                dispatch(loginError(user.message));
                return Promise.reject(user)
            } else {
                // If login was successful, set the token in local storage
                localStorage.setItem('id_token', user.token);
                let token = localStorage.getItem('id_token')
                console.log(token);
                // Dispatch the success action
                dispatch(receiveLogin(user));
            }
        }).catch(err => console.log("Error: ", err))
    }
}

and here's the POST request (I'm getting the values object from redux-form)
const token = localStorage.getItem('id_token');
const AuthStr = 'Bearer '.concat(token);

let headers ={
headers: { 'Content-Type':'application/json','Authorization' : AuthStr }
};

export default (async function showResults(values, dispatch) {
axios.post(BASE_URL + '/new', values, headers)
    .then(function (response) {
        console.log(values);
        console.log(response);
    })
    .catch(function (error) {
        console.log(token);
        console.log(values)
        console.log(error.response);
    });
});

P.P.S: if anyone has any suggestion for improving my code, feel free to comment.

A: You could also use a middleWare to check if the token has been expired. You even could update the token if it will almost expire. For example, you could do something shown below;
 export function jwtMiddleware({ dispatch, getState }) {
  return (next) => (action) => {
    switch (action.type) {
      case 'CHECK_AUTH_TOKEN' :
        if (getState().auth && getState().auth.token) {
          var tokenExpiration = jwtDecode(getState().auth.token).exp;
          var tokenExpirationTimeInSeconds = (tokenExpiration - moment(Math.floor(Date.now() / 1000)));
          if (tokenExpiration && tokenExpirationTimeInSeconds < 20) {
            history.push(i18next.t('translation:routes.auth.logout'));
          }
        }
      break;
      case 'UPDATE_AUTH_TOKEN' :
        if (getState().auth && getState().auth.token) {
          var tokenExpiration = jwtDecode(getState().auth.token).exp;
          var tokenExpirationTimeInSeconds = (tokenExpiration - moment(Math.floor(Date.now() / 1000)));
          if (tokenExpiration && tokenExpirationTimeInSeconds < 100 && tokenExpirationTimeInSeconds > 20) {
            if (!getState().auth.fetching) {
              return dispatch(refreshAuthToken(getState().auth));
            }
          }
        }
      break;
      case 'REFRESH_AUTH_TOKEN_FAIL' :
        if (getState().auth && getState().auth.token) {
          return dispatch(removeAuthToken(getState().auth)).then(response => {
            history.push(i18next.t('translation:routes.auth.logout'));
          });
        }
      break;
      }
    return next(action);
  }
}

A: JWT expiration can be checked in two ways. First of all you have to install jsonwebtoken package and require it at the top of your file. Thereafter, you can follow the below ways to check JWT expiration before sending any rest requests.
Option 1
var isExpired = false;
const token = localStorage.getItem('id_token');
var decodedToken=jwt.decode(token, {complete: true});
var dateNow = new Date();

if(decodedToken.exp < dateNow.getTime())
    isExpired = true;

Option 2
const token = localStorage.getItem('id_token');
jwt.verify(token, 'shhhhh', function(err, decoded) {
  if (err) {
    /*
      err = {
        name: 'TokenExpiredError',
        message: 'jwt expired',
        expiredAt: 1408621000
      }
    */
  }
});

Check the error of that method. If it is the TokenExpiredError then that means the token is expired.

A: Here is a solution with jwt-decode library by comparing the exp attributes in the JWT token with current time. (JWT token is simply a Base64 encoded string)

*

*Install jwt-decode (npm install jwt-decode --save)
 let token = localStorage.getItem(TOKEN);
  let decodedToken = jwt_decode(token);
  console.log("Decoded Token", decodedToken);
  let currentDate = new Date();

  // JWT exp is in seconds
  if (decodedToken.exp * 1000 < currentDate.getTime()) {
    console.log("Token expired.");
  } else {
    console.log("Valid token");
    result = true;
  }

IMPORTANT:  jwt-decode  doesn't validate the token, any well formed JWT can be decoded. You should validate the token in your server-side logic by using something like express-jwt, koa-jwt, Owin Bearer JWT, etc.


text:
Q: Spring Tool Suite change key binding autocompletion How do I change the keybinding for code autocompletion? Ctrl+Space is just horrible. I would like to have Alt+Space.
But under Window->Preferences->General->Keys->Content Assist I can not choose Alt+Space.

A: *

*Go to Window-> Preferences -> General -> Keys and type content assist.

*Copy this text -> Alt+Space.

*Right click on Binding text field.

*Paste.

*Apply, OK.

*Enjoy.


text:
Q: running an animation on a thread android i am trying to run a  simple button animation when the game is over
i have the following classes:
GameView
GameThread
public class GameView extends SurfaceView implements SurfaceHolder.Callback {
boolean gameover;GameThread gamethread;

public GameView(Context context, AttributeSet attrs) {
    super(context, attrs);
    gameover=true;

    getHolder().addCallback(this); // adding the callback (this) to the surface holder to intercept events

    setFocusable(true);// make the GamePanel focusable so it can handle events

}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
        int height) {

    Log.d("TAG", "surface changed");
}

@Override
public void surfaceCreated(SurfaceHolder holder) {

            gamethread=new GameThread(getHolder(),this);
            gamethread.setrunning(true);
            gamethread.start();

}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
    boolean retry=true;
    Log.d("TAG", "Surface destroyed entered");

    while(retry){
    try {
        gamethread.setrunning(false);
        gamethread.join();
        gamethread=null;
        Log.d("tag","thread is destroyed" );
        if(gamethread==null){
            Log.d("tag","thread is destroyed and null" );

        }
        retry=false;
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    }//end while
}//end method

public void update(){

    if(gameover){

        Button gameover_button = (Button) findViewById(R.id.gameover);
        Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.gameoveranimation);
        gameover_button.startAnimation(animation);

}

}//end update`

public class GameThread extends Thread  {
// desired fps

private boolean running;
private SurfaceHolder surfaceholder;
private GameView gameview;

public GameThread(SurfaceHolder surfaceHolder, GameView gameview){
    this.gameview=gameview;
    this.surfaceholder=surfaceHolder; //we need the surfaceholder since we need to lock surface before drawing

}
public void setrunning(boolean running){

    this.running=running;
}

@Override
public void run(){
    super.run();
    Canvas canvas;

        while(running){

        canvas=null;

        canvas = this.surfaceholder.lockCanvas();
        synchronized (surfaceholder) {
            if(canvas!=null){
                canvas.drawColor(Color.BLACK);
            this.gameview.Draw1(canvas);

            this.gameview.update();

            }//end if

            }
        }

        }finally{//in case of an exception
            if(canvas!=null){
            surfaceholder.unlockCanvasAndPost(canvas);
            }
                }//end finally
                        }//end loop

                        }//end run

}

<br>

everything works fine except the animation in the update method in the gameview class
the animation runs fine in the oncreate method
i know that my  problem is  related to thread but i don't know much about them
thx in advance
`

A: If your issue is that you need to call update on the UI thread, then you can use this:
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
    @Override
    public void run() {
        this.gameview.update();
    }
});

Also, it looks like you are looking for your game-over button as a child of your surface view. If that is not correct, you can find the view relative to the parent activity.
Activity activity = (Activity) getContext();
Button gameover_button = (Button) activity.findViewById(R.id.gameover);


text:
Q: Is it possible to closing copy text on QLPreviewController I develop Xamarin Forms app. And I use QLPreviewController for ios. I want to close copy text/text share, if document has text. Is it possible and how? I searched it as native. Some sources redirect me to UIDocumentInteractionControllerDelegate. But I didn't understand how can i do it.
Thanks in advance.

Edit:
My UIDocumentInteractionController implementation:
var firstController = UIApplication.SharedApplication.KeyWindow.RootViewController.ChildViewControllers.First().ChildViewControllers.Last().ChildViewControllers.First();
                    var navcontroller = firstController as UINavigationController;

                    var uidic = UIDocumentInteractionController.FromUrl(new NSUrl(file, true));
                    uidic.Delegate = new DocInteractionController(navcontroller);
                    uidic.PresentPreview(true);

public class DocInteractionController : UIDocumentInteractionControllerDelegate
    {
        UINavigationController navigationController;

        public DocInteractionController(UINavigationController _navigationController)
        {
            navigationController = _navigationController;
        }
    }

A: In your case it would be better to use WebView to preview files like pdf .
In forms
Create a custom webview
public class MyWebView : WebView
{
    public static readonly BindableProperty UriProperty = BindableProperty.Create(propertyName: "Uri",
            returnType: typeof(string),
            declaringType: typeof(MyWebView),
            defaultValue: default(string));

    public string Uri
    {
        get { return (string)GetValue(UriProperty); }
        set { SetValue(UriProperty, value); }
    }
}

in Android project

using Android.Content;
using Android.Net.Http;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Webkit;
using Android.Widget;
using App32;
using App32.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(MyWebView), typeof(CustomWebViewRenderer))]
namespace App32.Droid
{
    public class CustomWebViewRenderer : WebViewRenderer
    {
        Context _context;
        public CustomWebViewRenderer(Context context) : base(context)
        {
            _context = context;
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement != null)
            {
                Android.Webkit.WebView web_view = new Android.Webkit.WebView(_context);
                web_view.LoadUrl("https://drive.google.com/viewerng/viewer?embedded=true&url="+((MyWebView)Element).Uri);

                SetNativeControl(web_view);
                Control.Settings.JavaScriptEnabled = true;

            }
        }
    }

}

in iOS project
using System;
using App32;
using App32.iOS;
using Foundation;
using ObjCRuntime;
using UIKit;
using WebKit;
using Xamarin.Forms.Platform.iOS;

[assembly: Xamarin.Forms.ExportRenderer(typeof(MyWebView), typeof(MyWebViewRenderer))]
namespace App32.iOS
{
    public class MyWebViewRenderer : ViewRenderer<MyWebView, WKWebView>
    {
        WKWebView _wkWebView;

        protected override void OnElementChanged(ElementChangedEventArgs<MyWebView> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                var config = new WKWebViewConfiguration();
                _wkWebView = new WKWebView(Frame, config);

                SetNativeControl(_wkWebView);
            }

            if(e.NewElement!=null)
            {
                var webview = Element as MyWebView;

                var url = webview.Uri;

                Control.LoadRequest(new NSUrlRequest(new NSUrl("https://drive.google.com/viewerng/viewer?embedded=true&url=" + webview.Uri)));
            }

        }

    }

}

in xaml
Now you can use it in xaml like (you could open a new ContentPage that contains the WebView)
<StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">

        <local:MyWebView Uri="https://www.pdfpdf.com/samples/Sample1.PDF"/>

</StackLayout>


text:
Q: projective space and torus we defined the projective space as $\mathbb{S^2/Z_2}$ i.e. identify antipodal points and the torus as $\mathbb{R}^2 / \mathbb{Z}^2.$
And now I am concerned with their manifold structure-
In fact, I managed to cover both of them with three charts and it is also immediate to me that one chart cannot cover them, because they are compact, so their image would be compact under a homeomorphism. Despite, I don't see why two charts cannot cover them. Is there an easy argument for this?