Q:

The set of (1,1)-entries of matrices in an ideal of $M_n(R)$ is an ideal in the ring $R$

I'm reading the T. Y. Lam's A First Course in Noncommutative Rings, Theorem (3.1), page 32. In the proof, Lam asserts that the following fact is "easily seen":

Let $R$ be a ring with identity (not necessarily commutative) and let $I$ be an ideal in the usual ring $M_n(R)$ of the $n\times n$ matrices with entries in $R$. Show that $\mathfrak{A}=\{a_{11}\in R\,:\, (a_{ij})\in I\}$ is an ideal in $R$.

But I cannot understand it. If $a_{11}$ and $b_{11}\in \mathfrak{A}$, then, ok, $a_{11}+b_{11}\in \mathfrak{A}$ since $a_{11}+b_{11}$ is a $(1,1)$-entry of a matrix in $I$, namely, that matrix which is sum of the matrices who yield both $a_{11}$ and $b_{11}$. But how do I know that $a_{11}b_{11}\in \mathfrak{A}$? When I do the usual product of both matrices, I only know that
$$c_{11}=\sum_{i=1}^na_{1i}b_{i1}\in \mathfrak{A}...$$
but not that the isolated term $a_{11}b_{11}\in \mathfrak{A}$...

A:

First of all, you need to show that $a_{11}r\in\mathfrak{A}$ (and also $ra_{11}\in\mathfrak{A}$) for every $r\in R$, not just $r\in\mathfrak{A}$.  And in order to show this, you get to use the fact that $I$ is an ideal, so that if $A\in I$, then $AB\in I$ (and $BA\in I$) for every $B\in M_n(R)$.  As you say, when you multiply $A$ and $B$ you will get that $\sum_{i=1}^na_{1i}b_{i1}\in\mathfrak{A}$.  But the key here is that you can choose $B$ to be any matrix at all, so you can choose the entries $b_{i1}$ to be any elements of $R$ at all.  So you're free to just choose $b_{11}=r$ and $b_{1i}=0$ for $i\neq 1$, to get $a_{11}r\in \mathfrak{A}$.  Similarly, you can choose $B$ so that $BA\in I$ gives you $ra_{11}\in\mathfrak{A}$.


Q:

Installing SRAM X3 7-speed shifter with Acera derailleur : shifting stops at 4th cog

I've never installed one of these trigger shifters.  Here's what I'm doing:

Acera derailleur has chain on the smallest cog.
Mount trigger shifter on handlebar with its gear set to 7.
Run cable to and then through the rear derailleur.
Pull cable taut, gently, so the barrel-end is pulled into the trigger shifter and seats itself.
Tighten derailleur cable clamp.
Pedal the bike (mounted on stand).
Shift...shift...shift...shift.

The chain moves cog by cog up to the 4th cog and then the shifter trigger won't budge any further.

A:

SRAM shifters are generally not compatible with Shimano derailleurs. The reason is that they use different increments of cable pull per shift and derailleur actuation ratio (how far the cage moves sideways per mm of cable pulled).
SRAM X3 7 speed shifters pull 4.5mm of cable per shift. Actuation ratio is 1:1.1 resulting in ~5mm derailleur movement.
You don't say what Acera derailleur you have. Depending on how old it is it could (nominally) be 7, 8 or 9 speed, but all Shimano MTB derailleurs 9 speed and below have an actuation ratio of 1:1.7. For 7 speed the cable pull should be 2.7mm.
Source:
https://www.artscyclery.com/science-behind-the-magic/science-behind-the-magic-drivetrain-compatibility/
I think you probably have a several other adjustment issues - the cable is probably too slack, but the X3 shifter and Acera derailleur will not work together. Any Shimano 7 speed trigger shifter will work (because they all use the same actuation ratio).
When you get the correct shifters, use Park Tool Company's derailleur adjustment guides for (mostly) pain free setup:
https://www.parktool.com/blog/repair-help/rear-derailleur-adjustment
https://www.parktool.com/blog/repair-help/front-derailleur-adjustment


Q:

How can I instantiate `T` from inside a `Class` method?

Still learning the TypeScriptus.
I'm creating a Model and Collection system for a web app and I need my Collection class to be able to instantiate any Model subclass as passed when it's constructed, for example: new Collection<Post>() would create a list of Posts; and new Collection<Comment>() would create a list of Comments.
As you will see in the code pasted below I can do the axample as it stands and no error will come from it, but I want to instantiate any subclass of Model from inside the Collection class not just Post. How can I achieve this?
// A Model attributes form API
interface Attr {
    id: number;
    title: string;
}

// Base model class
abstract class Model {
    protected attr: Attr;
    public constructor(attr: Attr) {
        this.attr = attr;
    }
}

// An actual model to be used in the app
class Post extends Model {
    public constructor(attr: Attr) {
        super(attr);
        // other custom stuff, like API adapters, etc.
    }
}

// A collection of Model using type T
class Collection<T extends Model> {
    private collected: T[] = [];

    public async fetch(): Promise<Collection<T>> {
        const attrList: Attr[] = await new Promise<Attr[]>((resolve): void => {
            resolve([{
                id: 1,
                title: 'Post 1'
            }, {
                id: 2,
                title: 'Post 2'
            }] as Attr[]);
        });
        this.collected = attrList.map((attr: Attr): T => {
            // I can instantiate Post from here and cast it,
            // but I want to use whatever is passed in T instead
            return new Post(attr) as T;
        })
        return this;
    }

    public all(): T[] {
        return this.collected;
    }

}

const collection = new Collection<Post>();
const posts: Post[] = collection.all();

The key line is the hardcoded instatiation of Post inside of Collection.fetch() like this: return new Post(attr) as T;.
How do you go about instantiating a valid T that works, for example, with both Post and Comment classes?

A:

Your Collection<T> class instances need to hold onto an instance of a constructor for T.
Aside: it's probably not a good idea to use the name Attr for an interface because there is already a type in global scope named Attr which will either be a name collision or a name shadowing, neither of which are particularly pleasant to deal with.  I will change the name to MyAttr from here on.
When you construct a Collection<T>, you need to pass in a constructor of T objects that you can call with a MyAttr parameter, and the Collection<T> needs to hold onto that constructor to use inside the fetch() method implementation.  In Typescript, the type of such a constructor is new (attr: MyAttr) => T.  By using a parameter property we can represent the pass-in-and-hold-onto operation simply:
class Collection<T extends Model> {
  private collected: T[] = [];
  public constructor(private ctor: new (attr: MyAttr) => T) {}

(If we wanted to write that out, it would be like private ctor: new (attr: MyAttr) => T; public constructor(ctor: new (attr: MyAttr) => T) { this.ctor = ctor; })
Then inside the fetch() method we use this.ctor:
  public async fetch(): Promise<Collection<T>> {
    const attrList = await new Promise<MyAttr[]>(
      (resolve): void => {
        resolve([
          {
            id: 1,
            title: "Post 1"
          },
          {
            id: 2,
            title: "Post 2"
          }
        ]);
      }
    );
    this.collected = attrList.map(attr => new this.ctor(attr));
    return this;
  }

And that should work for you.  (Notice I removed your type assertion for the promise resolution... it's not necessary once you fix the name collision with the built-in Attr interface)
Finally, when you make collection, you pass in the Post constructor.  You don't need to manually specify the generic T as Post anymore, because the compiler will infer that for you:
const collection = new Collection(Post);
const posts: Post[] = collection.all();

Okay, hope that helps.  Good luck!
Link to code


Q:

is a decorator in python exactly the same as calling a function on a function?

I thought that doing
@f
def g():
   print 'hello'

is exactly the same as
def g():
   print 'hello'
g=f(g)

But, I had this code, that uses contextlib.contextmanager:
@contextlib.contextmanager
def f():
    print 1
    yield
    print 2
with f:
    print 3

which works and yields 1 3 2
And when I tried to change it into
def f():
    print 1
    yield
    print 2
f=contextlib.contextmanager(f)
with f:
    print 3

I get AttributeError: 'function' object has no attribute '__exit__'
What am I missing? is there some black magic specifically in contextlib.contextmanager, or do i misunderstand how decorators work in general?

A:

Yes, decorator is exactly same as calling a function and assigning to returned value
In this case error comes because you are not calling function, so correct code would be
def f():
    print 1
    yield
    print 2

f=contextlib.contextmanager(f)
with f():
    print 3

also I am not sure if you tested code, because decorator code you have given will fail due to same reason
@contextlib.contextmanager
def f():
    print 1
    yield
    print 2
with f:
    print 3

Error:
    with f:
AttributeError: 'function' object has no attribute '__exit__'


Q:

Learning AJAX, html code won't do anything

I have set up a servlet displaying usernames,passwords,wins,and losses for a checkersgame I wrote. I want to create a ajax program to access this page and create a table listing the users wins and losses (like a simple leader board). However my HTML code won't work and I can't see why. I can log into the page that I list as the variable url and see the xml file from the servlet. Any help is greatly appreciated.

    <button onclick = "requestUpdate()">Update</button>

Here is the servlet code
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class CheckersServlet
 */
@WebServlet("/CheckersServlet")
public class CheckersServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

/**
 * @see HttpServlet#HttpServlet()
 */
public CheckersServlet() {
    super();
    // TODO Auto-generated constructor stub
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    // TODO Auto-generated method stub
    response.setContentType("text/xml");
    PrintWriter out = response.getWriter();
    out.println("<?xml version='1.0'?>" );

    BufferedReader fReader = new BufferedReader(new FileReader("/Users/adamsturge991/desktop/checkersdatabase.txt"));
    String data = fReader.readLine();
    out.println("<CheckersData>");
    while(data != null)
    {
        out.println("<User>");
        out.println("<Username>");
        out.println(data);
        out.println("</Username>");
        data = fReader.readLine();
        out.println("<Password>");
        out.println(data);
        out.println("</Password>");
        data = fReader.readLine();
        out.println("<Wins>");
        out.println(data);
        out.println("</Wins>");
        data = fReader.readLine();
        out.println("<Losses>");
        out.println(data);
        out.println("</Losses>");
        out.println("</User>");
        data = fReader.readLine(); //get next username or null if end of database
    }
    out.println("</CheckersData>");
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
}

}

A:

This line:
var req = newXMLHttpRequest();

Needs a space after new, so:
var req = new XMLHttpRequest();

(Note also that continually updating div.innerHTML in your displayResult() function will not give good performance. Better to build up the required html in a string variable and then set div.innerHTML equal to that variable at the end.)


Q:

Should we use Work flows for field updates?

Is this recommended to use work flows for field update? I read that if we use work flows for field updates then triggers are get called twice. First before calling work flows(As per Order of Execution) and once after updating field using work flows(As per Order of Execution) to make sure standard validations.
So system is calling triggers twice in one transaction and it may lead to salesforce governor limit. So my question is in what circumstances should  we use work flow rules?
Thanks in advance

A:

This depends on what apex trigger code you already have in place. If it heavily uses things that have governor limits (like DML calls), then you could hit a governor limit when the trigger is called twice because of a worflow field update. But a trigger that cannot be called twice within one transaction without hitting the governor limits is probably written in a bad way and should be optimised anyway. Search for bulkification to get some ideas on that.
In general, you will want to use workflow field updates instead of updating fields via apex. First, workflow rules should always work with new Salesforce releases, whereas apex code could have to be updated to work with new realeases (although this does not happen often). Secondly, it is usually easier to change workflow rules than changing and deploying apex code.
If you do not have apex triggers, you don't have to worry at all.


Q:

C# Calling internal methods of an object passed as interface

I have an interface IFoo defining some functions, an abstract class FooBase implementing IFoo and some internal functions, and several classes Foo deriving from FooBase.
I also have a class Bar that should call a method from FooBase but gets its parameters passed as IFoo. So everything looking like this:
public interface IFoo
{
  // Some methods
}

public abstract class FooBase : IFoo
{
  // Methods from IFoo

  internal TInternalType SomeMethod();
}

public class Foo1 : FooBase
{
  // ...
}

public class Bar
{
  public void DoSomething(IFoo foo)
  {
    // This does not feel right:
    TInternalType myT = (foo as FooBase).SomeMethod();
  }
}

As already said, this does not feel right, since anybody could come along, write a class Baz implementing IFoo and calling DoSomething with this will fail.
I also found this question/solution to a similar problem about internal stuff with public interfaces, but that won't change the problem that some third party class implementing IFoo would cause problems, i.e. i still have a lying API.
Alternatively i could change the type of DoSomething to take a parameter of type FooBase and secure FooBase from third party classes by making the constructor internal, but i want to have only abstractions in my public API, not implementations.
So in short i'm asking: Is there a way for a library to only expose abstractions (i.e. the user of the library is only working with those) but still access internal members?
Background:
I'm writing a library that exposes some types and uses another library L to implement its functionality. The fact that L is used, is an implementation detail that i want to hide from my library's users, so when at some point for some reason i have to replace L by something else, my users won't notice.
I now have some of these Foo classes that will be exposed to my users, and one Bar class that will work with L. For each class Foo, a respective instance of a class from L has to be created; but the separate Foo classes are too different, they each need individual logic to create their respective L class.
That's why i defined an internal abstract method in FooBase and each Foo is implementing its own method to generate its class from L, so Bar can just call this one method to gets what it needs to work with L.
Maybe there's a completely different approach than an internal overloaded method.

A:

If you want to avoid exposing your base classes to the user, why not create another interface deriving from IFoo, calling it something like IFooWithSomeMethod, add a SomeMethod method to it, and implement that interface in FooBase?  Then Bar.DoSomething could take an IFooWithSomeMethod rather than a IFoo.
Btw, sorry for screwing up some of the names in the first pass.  Hopefully I've got it all straightened out now.

A:

The whole point of interfaces is to show the abilities of the implementation. If you need to access internal members of the implementation, you should let the consumers of the code know they are not really internal (either by following the other answers here, or for example with Interface Segregation and passing around only individual role interfaces), or keep them really internal. In your case I think it should be encapsulated in the FooBase class.
I suppose that the DoSomething method also does other things to the IFoo implementation. Whatever Bar does with the internal type returned from the internal method should probably happen in FooBase in one of those other IFoo methods instead. The guiding principle here is Tell, don't ask.


Q:

binary search tree postorder traversal by iteration

i implemented an iterative post-order algorithm along with pre and inorder . but the iterative post-order is not working.all my efforts are in vain to spot the bug.
the program crashes before printing the last node data of tree in post-order.
this is the code snippet.
t=root;

    while(t!=NULL || !st.empty())
    {
        if(t!=NULL)
        {
            if(t->r!=NULL)
                st.push(t->r);
            st.push(t);
            t=t->l;
        }
        else
        {
            t=st.top();
            st.pop();
            if(t->r!=NULL && t->r==st.top())
            {
                st.pop();
                st.push(t);
                t=t->r;
            }
            else
            {
                cout<<t->data<<" ";
                t=NULL;
            }
        }
    }

more info: st is STL stack and consider root as global(in my code, above snippet is a part of a class and so is root variable )

A:

The problem is in this line:
if(t->r!=NULL && t->r==st.top())

the issue is that the stack may be empty at this point, in which case calling st.top() will cause the program to crash.
You can fix this by changing the line to:
if(t->r!=NULL && !st.empty() && t->r==st.top())

Example
If your tree has root connected to NULL on its left, and A on its right then the program will:

push A (stack now has A)
push root (stack now has A,root)
pop root (stack now has A)
pop A (stack is now empty)
push root (stack now has root)
push A (stack has root,A)
pop A and print A's data (stack has root)
pop root (stack is now empty)
At this stage the program has an empty stack and t->r!=NULL so it will access st.top


Q:

How to remove a filename from the list of path in Shell

I would like to remove a file name only from the following configuration file.
Configuration File -- test.conf
knowledgebase/arun/test.rf
knowledgebase/arunraj/tester/test.drl
knowledgebase/arunraj2/arun/test/tester.drl

The above file should be read. And removed contents should went to another file called output.txt
Following are my try. It is not working to me at all. I am getting empty files only.
#!/bin/bash
file=test.conf
while IFS= read -r line
do
#       grep --exclude=*.drl line
#       awk 'BEGIN {getline line ; gsub("*.drl","", line) ; print line}'
#       awk '{ gsub("/",".drl",$NF); print line }' arun.conf
#       awk 'NF{NF--};1' line arun.conf
echo $line | rev | cut -d'/' -f 1 | rev >> output.txt
done < "$file"

Expected Output :
knowledgebase/arun
knowledgebase/arunraj/tester
knowledgebase/arunraj2/arun/test

A:

There's the dirname command to make it easy and reliable:
#!/bin/bash
file=test.conf
while IFS= read -r line
do
    dirname "$line"
done < "$file" > output.txt

There are Bash shell parameter expansions that will work OK with the list of names given but won't work reliably for some names:
file=test.conf
while IFS= read -r line
do
    echo "${line%/*}"
done < "$file" > output.txt

There's sed to do the job — easily with the given set of names:
sed 's%/[^/]*$%%' test.conf > output.txt

It's harder if you have to deal with names like /plain.file (or plain.file — the same sorts of edge cases that trip up the shell expansion).
You could add Perl, Python, Awk variants to the list of ways of doing the job.


Q:

Windows service using BackgroundService cannot be stopped

I'm using a Net Core 3.X BackgroundService and after publishing my code, I've installed the executable generated as a Windows Service.
On my ExecuteAsync method I have some code like this:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    while (!stoppingToken.IsCancellationRequested)
    {
        //do something

        if(someConditionIsTrue)
        {
            await this.StopAsync(new CancellationToken());
        }
    }
}

That manual call on StopAsync stops the execution and exits from while loop, but when I go to services.msc I see that my Windows Service is still in running state although is not executing anything.
How can I stop the service automatically and not calling to "cmd \c sc stop..."?
Thanks

A:

Your BackgroundService is stopping correctly, but the application is not being stopped.
To stop the application from a background service, inject a IHostApplicationLifetime and call it as such:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
  while (!stoppingToken.IsCancellationRequested)
  {
    //do something

    if (someConditionIsTrue)
    {
      _hostApplicationLifetime.StopApplication();
    }
  }
}

You don't need to call this.StopAsync because that will (eventually) be called by StopApplication.


Q:

Excel - Delete all one-to-one rows between two columns

Problem: I have Column A and Column B. Column A is predictable, there are thousands of column A rows. Column B has variying rows per Column A. For example, Column A may have the value REQ_000021 with 5 rows in Column B. Those are okay. The rows I need deleted are the ones where there is only one Column B per Column A.
I know this isn't a typical thing that people do so I couldn't find a VB script out there to do this.
I would post a picture if the site would allow me to. Need 15 rep points first.
Edit:
I just learned how to do newlines on stackoverflow , so here this goes:

Col A    Col B
----------------------------------
Scott    Us
         Germany
         Spain
----------------------------------
brian    US
----------------------------------
Mark     US
----------------------------------
         Italy
Tim      Portugal
         Ireland
----------------------------------

Delete brian and Mark because there is one row for Column A and Column B.
Leave Scott and Tim alone because there is more than one Column B row per column A row. Keep in mind that Column A for Scott and Tim are large, merged rows.
That's what I'm trying to get done.

Edit:
per Scott's answer, this is the output:
I captioned some markings for clarity for anyone else who is looking at this.

Edit:
This following VB script will Delete any row that has the "DELETE" value in column C.
I used it as a macro in Excel. For those who are new to macros, enable Developer view in Excel 2007 to gain access to the view that lets you toggle to the VB screen.

Sub deleteDeleteString()
Dim rng As Range, cell As Range, del As Range
Dim strCellValue As String
Set rng = Intersect(Range("C:C"), ActiveSheet.UsedRange)
For Each cell In rng

strCellValue = (cell.Value)
'if DELETE is found in a cell in Column C greater than 0 times, delete it's entire row
If InStr(strCellValue, "DELETE") > 0 Then
If del Is Nothing Then
Set del = cell
Else: Set del = Union(del, cell)
End If
End If
Next cell
On Error Resume Next
del.EntireRow.delete
End Sub

A:

Here is the new formula based on your edit of how your data is formatted.
Place the following formula in C1 and run down the column to get the rows to be deleted:
=IF(OR(ISBLANK(A1),ISBLANK(A2)),"","DELETE")

You may or may not want to un-merge the cells in column A first, but it shouldn't matter given the rules of how Excel handles merged cells. I tested this on the data set you provided and it worked with or without merging the cells.
I am not providing a VBA solution because you don't need one here. Run this formula than filter on Column C for "DELETE" and delete your rows.


Q:

What is the meaning of もんな

Reading "プラチナデータ" by 東野圭吾.
Not clear on the meaning of:
"俺、何度も彼女を殺しそうになったもんな" -
"I often almost killed her ... (monna?)"
What is "monna"? I suppose "mono nara" ("if that thing"), but then I don't understand the whole sentence - is it "If I often almost killed her"?

A:

More than anything, it is a colloquial way of adding the nuance of "retrospective confession or boasting" in my own words.


Q:

Is OAEP reversible?

Given nothing more than some integer $m =$ OAEP($M$), is it possible to recover the original plaintext $M$? In other words, without being given the hash functions or the random string used for encoding, or even the length of it.
EDIT: This is being used in tandem with RSA, but I don't know the hash functions that OAEP usually uses with RSA; they might be public, for all I know.

A:

If you know the hash functions, yes.  If the hash functions are secret, no—but how would you come into a situation where OAEP is being used with a secret hash function?
For any hash functions $G$ and $H$, OAEP is a fixed permutation involving no secret keys.  Specifically, given a message $m$ and randomization $r$, OAEP returns $(a, b)$ where
\begin{align}
  a &= m \oplus G(r), \\
  b &= r \oplus H(a),
\end{align}
which can be inverted by
\begin{align}
  r &= b \oplus H(a), \\
  m &= a \oplus G(r).
\end{align}
So if you have $(a, b)$ and you can compute $G$ and $H$, you can recover $m$ (and $r$).  This is exactly what RSAES-OAEP decryption does, after it completes the RSA private key operation.


Q:

Single statement across multiple lines in VB.NET without the underscore character

Is there a way to have a statement across multiple lines without the underscore character?
It is really annoying in multi-line strings such as SQL statements, and especially LINQ queries.
Beside from the ugliness and difficulty when changing a line (nothing lines up anymore), you can't use comments in the middle of the multi-line statement.
Examples of my daily personal hell.
dim results = from a in articles _
              where a.articleID = 4 _ ' articleID     - Nope, can't do this
              select a.articleName

dim createArticle as string = _
    "Create table article " & _
    "    (articleID int " & _
    "    ,articleName varchar(50) " & _
    "    )"

A:

No, you have to use the underscore, but I believe that VB.NET 10 will allow multiple lines w/o the underscore, only requiring if it can't figure out where the end should be.

A:

For most multiline strings using an XML element with an inner CDATA block is easier to avoid having to escape anything for simple raw string data.
Dim s as string = <s><![CDATA[Line 1
line 2
line 3]]></s>.Value

Note that I've seen many people state the same format but without the wrapping "< s >" tag (just the CDATA block) but visual studio Automatic formatting seams to alter the leading whitespace of each line then.
I think this is due to the object inheritance structure behind the Linq "X" objects. CDATA is not a "Container", the outer block is an XElement which inherits from XContainer.

A:

Starting with VB.NET 10, implicit line continuation is supported for a number of syntax elements (see Statements in Visual Basic: Continuing a Statement over Multiple Lines). The concatenation operator (&) is in the list of syntax elements, that support implicit line continuation. Interspersed comments are supported as well, so your second example could be rewritten as:
dim createArticle as string =
    "Create table article " &
    "    (articleID int " &           ' Comment for articleID
    "    ,articleName varchar(50) " & ' Comment for articleName
    "    )"

Implicit line continuation also works for query operators, with a few restrictions:

Before and after query operators (Aggregate, Distinct, From, Group By, Group Join, Join, Let, Order By, Select, Skip, Skip While, Take, Take While, Where, In, Into, On, Ascending, and Descending). You cannot break a line between the keywords of query operators that are made up of multiple keywords (Order By, Group Join, Take While, and Skip While).

Again, interspersed comments are allowed, so your first example can be rewritten as:
dim results = from a in articles
              where a.articleID = 4  ' articleID - now perfectly legal
              select a.articleName


Q:

compare date split across columns

I am querying tables from Microsoft SQL 2008 which have date split across 3 columns: day, month and year. Unfortunately, I do not have control over this because data is coming in to the database daily from a 3rd party source in that format.
I need to add between to a where clause so user can pull records within a range.  Would be easy enough if date was in a single column but finding it nearly impossible when its split across three columns.
To display the date, I am doing a
CAST(
    CAST(year as varchar(4)) + '-' +
    CAST(month as varchar(2)) + '-' +
    CAST(day as varchar(2))
as date) AS "date"`

in a select. I tried to put it as a parameter for datediff function or just the regular between but get no results.

A:

Without access to change the table, you can use a subquery to construct the date before the filtration is applied:
SELECT x.*
  FROM (SELECT CAST(CAST(year as varchar(4)) + '-' +
                    CAST(month as varchar(2)) + '-' +
                    CAST(day as varchar(2)) AS date) AS [date]
                    ...
          FROM ...) x
 WHERE x.[date] BETWEEN ? AND ?

If using SQL Server 2005+, you can use a Common Table Expression (CTE) instead -- but there's no performance difference between using a CTE vs the subquery approach:
WITH example AS (
   SELECT CAST(CAST(year as varchar(4)) + '-' +
               CAST(month as varchar(2)) + '-' +
               CAST(day as varchar(2)) AS date) AS [date]
               ...
     FROM ...)
SELECT x.*
  FROM example x
 WHERE x.[date] BETWEEN ? AND ?

Caveats:
Because the dates are being constructed on the fly, this will never perform as well as if the values were stored as DATE or DATETIME -- an index on the year, month or day columns can not be utilized.  Options to consider would be an indexed view (AKA materialized view), or computed column.


Q:

What is the specific requirement to use Dagger2 in any android application? What are the actual benefits of using dagger2 in an android application?

I read the dagger 2 documentation but still not able to find that in what condition I should use dagger2 in my application and what are the benefits of its implementation?

A:

1.) to use Dagger2, you need to include it as a dependency in your project.
annotationProcessor 'com.google.dagger:dagger-compiler:2.9'
compile 'com.google.dagger:dagger:2.9'
provided 'org.glassfish:javax.annotation:10.0-b28'

Then you can use Dagger2.

2.) Whenever you have a class which is the dependency of another class.
So if you have something like this:
public int getNewRandomNumber() {
    return new Random().nextInt(5000);
}

Then you have an implicit dependency on Random and it is not mockable.
So you might want to provide this as a dependency to the method instead:
public int getNewRandomNumber(Random random) {
   return random.nextInt(5000);
}

But you might be using Random in a bunch of places, so you might want to provide it to the class itself:
public class RandomGenerator {
    private final Random random;

    public RandomGenerator(Random random) {
        this.random = random;
    }
}

After which the question surfaces: if you need an instance of RandomGenerator, where are you getting Random from?
Surely this is stupid:
RandomGenerator gen = new RandomGenerator(new Random());

Wouldn't it be nicer to do either this:
RandomGenerator randomGenerator = component.randomGenerator();

or
@Inject
RandomGenerator randomGenerator;

Well apparently with Dagger it's pretty easy
@Module
public class RandomModule {
    @Provides
    @Singleton
    Random random() {
        return new Random();
    }
}

@Singleton
@Component(modules={RandomModule.class})
public interface SingletonComponent {
    Random random();
    RandomGenerator randomGenerator();
}

then
@Singleton
public class RandomGenerator {
    private final Random random;

    @Inject
    public RandomGenerator(Random random) {
        this.random = random;
    }
}

or
@Singleton
public class RandomGenerator {
    @Inject
    Random random;

    @Inject
    public RandomGenerator() {
    }
}

You can read more about dependency injection here


Q:

How would one represent/model the effect of air resistance on horizontal motion?

Evidently, there are formulas that allow us to represent the effect of air resistance on the velocity of an object in free fall but how would one calculate the effect of air resistance on horizontal motion, for instance how much air resistance hinders a humans speed or so ?

A:

Nothing on how to think about air resistance depends on the direction you move into. Same usual representations applying to a free fall are used for other purposes. Mainly a force that is $\sim\vec v$ in case of a laminar regime or $\sim|\vec v|^2 \hat v$ in a turbulent one.


Q:

Toolbar home up button pointing left in RTL

Home up button in RTL is pointing left on Android 5.1(API 22) and lower:

But on Android 6.0(API 23) everything is ok and it's pointing right.

How to solve that?

A:

In  your style.xml put:
 <item name="homeAsUpIndicator">@drawable/ic_arrow_back</item>

And create a drawable-ldrtl-xhdpi-v17 folder in res and put proper drawable (RTL drawable).


Q:

Client sends 500 Bytes, but server receives 244 Bytes - Socket Programming?

I am trying to implement the Stop-and-Wait ARQ for UDP. According to the Stop-and-Wait conventions, I toggle my ACK between 0 and 1.
A correct ACK is defined as a correct sequence number (either 0 or 1) AND a correct message length.
The following snippets are my related parts of the code.
Client Side
// transmission function
void str_cli(FILE *fp, int sockfd, long *len, struct sockaddr *addr, int addrlen)
{
    char *buf;
    long lsize, ci;
    char sends[DATALEN];
    struct ack_so ack;
    int n, slen;
    float time_inv = 0.0;
    struct timeval sendt, recvt;
    ci = 0;

    int prev_msg_acked = TRUE;
    int ack_number = 1;

    fseek(fp, 0, SEEK_END);
    lsize = ftell (fp);
    rewind(fp);
    printf("The file length is %d bytes\n", (int)lsize);
    printf("the packet length is %d bytes\n", DATALEN);

    // allocate memory to contain the whole file.
    buf = (char *) malloc(lsize);
    if (buf == NULL)
       exit (2);

    // copy the file into the buffer.
    fread(buf, 1, lsize, fp);

    // the whole file is loaded in the buffer
    buf[lsize] ='\0'; // append the end byte
    gettimeofday(&sendt, NULL); // get the current time
    while(ci <= lsize)
    {
        if (prev_msg_acked) // only transmits when previous message has been acknowledged
        {
            if ((lsize+1-ci) <= DATALEN) // final string
                slen = lsize+1-ci;
            else // send message of length DATALEN
                slen = DATALEN;
            memcpy(sends, (buf+ci), slen);

            /*************** SEND MESSAGE ***************/
            if((n = sendto(sockfd, &sends, strlen(sends), 0, addr, addrlen)) == -1) {
                printf("send error!\n"); // send the data
                exit(1);
            }

            // update the expected ACK number
            if (ack_number == 1)
                ack_number = 0;
            else
                ack_number = 1;

            ci += slen;
        }

        /*************** RECEIVE ACK ***************/
        if ((n = recvfrom(sockfd, &ack, 2, 0, addr, &addrlen)) == -1)
        {
            printf("error when receiving\n");
            exit(1);
        }

        if (ack.num != ack_number || ack.len != slen) // ACK wrong
        {
            printf("%i %i expected\n", ack_number, strlen(sends));
            printf("%i %i received\n", ack.num, ack.len);
            printf("ACK check fails, retransmission...\n");
            prev_msg_acked = FALSE;
        }
        else
            prev_msg_acked = TRUE;
    }
}

Server Side
// transmitting and receiving function
void str_ser(int sockfd, int *ack_number)
{
    FILE *fp;
    char buf[BUFSIZE];
    char recvs[DATALEN];
    int end = 0, n = 0;
    long lseek = 0;
    struct ack_so ack;

    struct sockaddr_in addr;
    socklen_t len = sizeof(struct sockaddr_in);

    printf("receiving data!\n");

    while(!end)
    {
        // receive the packet
        if ((n = recvfrom(sockfd, &recvs, DATALEN, 0, (struct sockaddr *)&addr, &len)) == -1)
        {
            printf("error when receiving\n");
            exit(1);
        }

        // toggle the ack_number
        if (*ack_number == 1)
            *ack_number = 0;
        else
            *ack_number = 1;

        // if the last bit of the received string is the EoF
        if (recvs[n-1] == '\0')
        {
            end = 1;
            n--;
        }

        memcpy((buf+lseek), recvs, n);
        lseek += n;

        // up to here, successfully received a packet
        // send ACK back
        ack.num = *ack_number;
        ack.len = strlen(recvs);
        printf("%i %i as ACK sent\n", ack.num, ack.len);
        if ((n = sendto(sockfd, &ack, 2, 0, (struct sockaddr *)&addr, len)) == -1)
        {
            printf("ACK send error!\n");
            exit(1);
        }
    }

    if ((fp = fopen ("myUDPreceive.txt", "wt")) == NULL)
    {
        printf("File doesn't exit\n");
        exit(0);
    }

    fwrite (buf, 1, lseek, fp); //write data into file
    fclose(fp);
    printf("A file has been successfully received!\nThe total data received is %d bytes\n", (int)lseek);
}

With this implementation, I ended up with the following results:
Client Side Results
$ ./cli localhost
The file length is 59792 bytes
the packet length is 500 bytes
0 500 expected
0 244 received
ACK check fails, retransmission...

Server Side Results
$ ./ser
receiving data!
0 244 as ACK sent

As can be seen, the client sends out a message of length 500, and thus expects an ACK to be 0 500. However, the server receives a message of length 244, and sends back an ACK 0 244. Since they do not match, the current implementation simply stops there.
Why would this length difference happen?

A:

In your client, you are doing
sendto(sockfd, &sends, strlen(sends), 0, addr, addrlen)

what you want is
sendto(sockfd, &sends, slen, 0, addr, addrlen)

strlen is problematic for two reasons:
(1) You do not null-terminate the buffer, and, more importantly,
(2) You are sending binary data which probably has a null byte as its 245 byte.
Rule of thumb: never use string functions on binary data.

A:

You should probably not be using strlen to determine the length of the data on either end, as that will prevent you from being able to send any binary data. Also, on the server it looks like you are expecting there to only be a 0 byte at the end of the data if it is the end of the file, so your strlen call is going to give you unreliable results in all other cases as well. Use the return value of recvfrom to determine how much data you received.
Another issue with your code is this:
buf = (char *) malloc(lsize);
...
buf[lsize] ='\0'; // append the end byte

You're allocating a memory buffer equal to the size of your file, and then setting a 0 byte past the end of that memory, which will cause you problems in the long-run. You should allocate an extra byte for that, so make it:
buf = (char *) malloc(lsize+1);
...
buf[lsize] ='\0'; // append the end byte

Update:
After reviewing your full code, I see the real problem:
struct ack_so
{
    uint8_t num; // the sequence number
    uint8_t len; // the packet length
};

ack_so::len is an 8-bit unsigned integer, which has a value range of 0-255, so 500 will overflow that value, giving you 244.
You should make len a uint32_t


Q:

The probability of rolling 4 dice and getting a 6.

The probability of rolling 2 dice and getting a 6 on either one of the die or both is   : 11/36 or about  0.305.
Also I calculate the probability of rolling 4 dice and getting a 6 on either one, two, three or all four dice is :  421/1296 or about 0.32.
Is that correct?  I am just surprised to find both the probabilities so close together.
Thank you.

A:

Method #$1$ - split it into disjoint events, and add up their probabilities:
$$\sum\limits_{n=1}^{4}\binom4n\cdot\left(\frac16\right)^{n}\cdot\left(1-\frac16\right)^{4-n}$$

Method #$2$ - calculate $1$ minus the probability of the complementary event:
$$1-\left(1-\frac16\right)^{4}$$

The result in both cases is: $$\frac{671}{1296}$$


Q:

Syntax error near AutoIncrement with SQLite Database creation

It's me again, the guy working with SQLite-net.  I had my code working when I did not have AutoIncrement on my Primary Keys of the tables.  I wanted to AutoIncrement the keys so I reconstructed the Tables like this:
using SQLite;

namespace VehicleTracks.Models
{
    public class vehicles
    {
        [PrimaryKey, AutoIncrement]
        public int ID { get; set; }
        public string VehID { get; set; }
        public string VehYear { get; set; }
        public string VehMake { get; set; }
        public string VehModel { get; set; }
        public string VehColor { get; set; }
        public string EngineID { get; set; }
        public System.DateTime PurchaseDate { get; set; }
        public string SellerName { get; set; }
        public string SellerStreet { get; set; }
        public string SellerCityStateZip { get; set; }
        public string VehOptions { get; set; }
        public string OdomInitial { get; set; }
        public string VehBodyStyle { get; set; }
        public float PurchaseCost { get; set; }
        public byte[] VehPhoto { get; set; }
        public string VehType { get; set; }
        public string Sold { get; set; }
    }
}

Now when an attempt is made to create the Tables, I get "Syntax Error near AutoIncrement".  I tried leaving off AutoIncrement and it does not appear to increment the ID without it.
I'm probably missing something stupid.

A:

Nothing stupid about your code; matches the code samples on https://github.com/praeclarum/sqlite-net alright. But apparently the code samples are wrong, considering this similar problem:
Android table creation Failure (near "autoincrement": syntax error)?
The problem was solved by removing AutoIncrement. Or to quote http://www.sqlite.org/faq.html#q1 :

Short answer: A column declared INTEGER PRIMARY KEY will autoincrement.

(Please double-check whether column ID actually has type INTEGER PRIMARY KEY once the table has been created.)

Longer answer: If you declare a column of a table to be INTEGER PRIMARY KEY, then whenever you insert a NULL into that column of the table, the NULL is automatically converted into an integer which is one greater than the largest value of that column over all other rows in the table, or 1 if the table is empty.

Make sure your INSERT statements do not contain an explicit value (other than NULL) for column ID, otherwise the column will not auto-increment. If that is not possible in SQLite-net (you may need a debugger here), then that may well be a bug. Though it would be surprising that nobody else has ever ran into this.
Maybe you need to make property ID nullable (i.e. use type int?; yes, with the question mark). Mind you, I'm only guessing here; you may need to experiment a bit.


Q:

References for use of symplectic geometry in statistics?

I have heard that many problems in Mathematical Statistics can be stated and solved in terms of Symplectic Geometry. Unfortunately this was a pretty vague statement and I am interested in something more concrete. Also there seem to be some books written form this perspective, but I couldn't find any.

A:

A direct connection would be unexpected: the two fields appear to have little in common.  For example, a modern introduction to symplectic geometry published by the American Mathematical Society appears to make no mention of mathematical statistics at all.
At best it seems any connection would come through mathematical physics.  A symplectic geometry on phase space naturally arises in the Hamiltonian formulation of classical mechanics and that in turn can be used to explore global properties of physical systems.  The study of periodic and near-periodic orbits becomes somewhat statistical (e.g., ergodic theorems).  When applied to a system with many degrees of freedom it would conceivably relate some aspects of symplectic geometry to thermodynamics, which is inherently a statistical theory

A:

I know nothing whatsoever about symplectic geometry, but a bit of googling brought up a 1997 article in the Journal of Statistical Planning & Inference by Barndorff-Nielsen & Jupp, which contains this quote:

Some other links between statistics and symplectic geometry have been discussed
  by Friedrich and Nakamura. Friedrich (1991) established some connections between
  expected (Fisher) information and symplectic structures. However, his approach and
  results are quite different from those considered here. Nakamura (1993, 1994) has
  shown that certain parametric statistical models in which the parameter space M is an
  even-dimensional vector space (and so has the symplectic structure of the cotangent
  space of a vector space) give rise to completely integrable Hamiltonian systems on M.

The cited refs are:

Friedrich, T., 1991. Die Fisher-lnformation und symplectische Strukturen. Math. Nachr. 153: 273-296.
Nakamura, Y., 1993. Completely integrable gradient systems on the manifolds of Gaussian and multinomial
distributions. Japan. J. Ind. Appl. Math. 10: 179-189.
Nakamura, Y., 1994. Gradient systems associated with probability distributions. Japan. J. Ind. Appl. Math. 11: 21-30.

The article's Introduction says B-N & others have used differential geometry as an approach to statistical asymptotics. Symplectic geometry is a branch of differential geometry (according to Wikipedia). A Google Books search finds several books about the application of differential geometry to statistics and related fields such as econometrics.


Q:

How to add SVG element from String to DOM

I would like to add SVG which includes rect and use tags from a string to the DOM.
I doesn't seams to work the way I do.

  var documentAsString =
  '<?xml version="1.0" encoding="UTF-8"?>\
   <document xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\
    <svg id="container" >\
     <g xmlns:xlink="http://www.w3.org/1999/xlink">\
      <rect x="50" y="50" width="50" height="50" fill="red"/>\
      <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#shape" x="200" y="50" fill="blue"></use>\
     </g>\
    </svg>\
   </document>\
  ';

  var newDocument = (new DOMParser()).parseFromString(documentAsString, "text/xml");
  var container = newDocument.getElementById("container");
  var useContainer = document.getElementById('use-container');

  useContainer.removeChild(useContainer.firstElementChild);
  useContainer.appendChild(container.getElementsByTagName('g')[0]);
 <svg>
  <defs>
   <g id="shape">
    <rect x="50" y="50" width="50" height="50" />
    <circle cx="50" cy="50" r="50" />
   </g>
  </defs>

  <use xlink:href="#shape" x="50" y="50" />
  <g id="use-container" xmlns:xlink="http://www.w3.org/1999/xlink">
   <rect x="10" y="10" width="50" height="50" fill="red"></rect>
  </g>
 </svg>

A:

The SVG element needs to be in the svg namespace i.e. have an xmlns attribute with the appropriate value...

  var documentAsString =
  '<?xml version="1.0" encoding="UTF-8"?>\
   <document xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\
    <svg xmlns="http://www.w3.org/2000/svg" id="container" >\
     <g xmlns:xlink="http://www.w3.org/1999/xlink">\
      <rect x="50" y="50" width="50" height="50" fill="red"/>\
      <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#shape" x="200" y="50" fill="blue"></use>\
     </g>\
    </svg>\
   </document>\
  ';

  var newDocument = (new DOMParser()).parseFromString(documentAsString, "text/xml");
  var container = newDocument.getElementById("container");
  var useContainer = document.getElementById('use-container');

  useContainer.removeChild(useContainer.firstElementChild);
  useContainer.appendChild(container.getElementsByTagName('g')[0]);
 <svg>
  <defs>
   <g id="shape">
    <rect x="50" y="50" width="50" height="50" />
    <circle cx="50" cy="50" r="50" />
   </g>
  </defs>

  <use xlink:href="#shape" x="50" y="50" />
  <g id="use-container" xmlns:xlink="http://www.w3.org/1999/xlink">
   <rect x="10" y="10" width="50" height="50" fill="red"></rect>
  </g>
 </svg>


Q:

How is memory garbage collected in app engine (python) when iterating over db results

I have some code that iterates over DB entities, and runs in a task - see below.
On app engine I'm getting Exceeded soft private memory limit error, and indeed checking memory_usage().current() confirms the problem. See below for output from logging statement. It seems that every time a batch of foos is fetched the memory goes up.
My question is: why is the memory not being garbage collected?  I would expect, that in each iteration of of the loops (the while loop, and the for loop, respectively) the re-use of the name foos and the foo would cause the objects to which foos and foo used to point would be 'de-referenced' (i.e. become inaccessible) and therefore become eligible for garbage collection, and then be garbage collected as memory gets tight. But evidently that it not happening.
from google.appengine.api.runtime import memory_usage

batch_size = 10
dict_of_results = {}
results = 0
cursor = None

while True:
  foos = models.Foo.all().filter('status =', 6)
  if cursor:
     foos.with_cursor(cursor)

  for foo in foos.run(batch_size = batch_size):

     logging.debug('on result #{} used memory of {}'.format(results, memory_usage().current()))
     results +=1

     bar  = some_module.get_bar(foo)

     if bar:
        try:
           dict_of_results[bar.baz] += 1
        except KeyError:
           dict_of_results[bar.baz] = 1

     if results >= batch_size:
        cursor = foos.cursor()
        break

  else:
     break

and in some_module.py
def get_bar(foo):

  for bar in foo.bars:
    if bar.status == 10:
       return bar

  return None

Output of logging.debug (shortened)
on result #1 used memory of 43
on result #2 used memory of 43
.....
on result #20 used memory of 43
on result #21 used memory of 49
.....
on result #32 used memory of 49
on result #33 used memory of 54
.....
on result #44 used memory of 54
on result #45 used memory of 59
.....
on result #55 used memory of 59
.....
.....
.....

on result #597 used memory of 284.3
Exceeded soft private memory limit of 256 MB with 313 MB after servicing 1 requests total

A:

It looks like your batch solution is conflicting with db's batching, resulting in a lot of extra batches hanging around.
When you run query.run(batch_size=batch_size), db will run the query until completion of the entire limit. When you reach the end of the batch, db will grab the next batch. However, right after db does this, you exit the loop and start again. What this means is that batches 1 -> n will all exist in memory twice. Once for the last queries fetch, once for your next queries fetch.
If you want to loop over all your entities, just let db handle the batching:
foos = models.Foo.all().filter('status =', 6)
for foo in foos.run(batch_size = batch_size):
  results +=1
  bar  = some_module.get_bar(foo)
  if bar:
    try:
      dict_of_results[bar.baz] += 1
    except KeyError:
      dict_of_results[bar.baz] = 1

Or, if you want to handle batching yourself, make sure db doesn't do any batching:
while True:
  foo_query = models.Foo.all().filter('status =', 6)
  if cursor:
    foo_query.with_cursor(cursor)
  foos = foo_query.fetch(limit=batch_size)
  if not foos:
    break

  cursor = foos.cursor()


Q:

How to add a line to the bottom of my table?

I'm using Java Swing with JasperReports. In Jasper I have items that are in Band: Details. I created around them lines (top, left, right). The problem is the line at the bottom.
Report Layout

When I put in Page footer and Run it - the line doesn't close the square. How I can close this square and independently of how many items I have?
Current output, with expect result

A:

To add the border at end of table in each page use the columnFooter band and set isFloatColumnFooter="true" on jasperReport tag
Example
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Example" pageWidth="595" pageHeight="842" columnWidth="500" leftMargin="20" rightMargin="20" topMargin="30" bottomMargin="30"  isFloatColumnFooter="true" uuid="43c90ca5-f3c3-4dda-8423-9ff1442f90e3">
    .....
   <columnFooter>
    <band height="2">
        <line>
            <reportElement x="0" y="0" width="555" height="1" uuid="1c32f6e5-414a-428d-8b06-35cd80e8dff6"/>
        </line>
    </band>
   </columnFooter>
</jasperReport>

To add the border at the end of table (not on each page if it overflows) use a dummy group and the groupFooter band
Example
<group name="lastBorderLine">
    <groupExpression><![CDATA["dummy"]]></groupExpression>
    <groupFooter>
        <band height="2">
            <line>
                <reportElement x="0" y="0" width="555" height="1" uuid="3510fdc6-0f30-4ec9-8e17-ac51fd4012c1"/>
            </line>
        </band>
    </groupFooter>
</group>

A:

Solved, by adding Group.
I have Band: Detail, and there lines in the top and on the botton of the detail (to close the rectangle). Then I added Group, under Detail Band and that's all
P.S. I was follow @YasuyukiUno instructions


Q:

Why does using an Object Initializer keep an object alive?

I recently came across this SO article and tweaked it for my scenario which follows:
using System;
using System.Collections.Generic;

namespace ConsoleApplication18
{
    class Program
    {
        static void Main(string[] args)
        {
            Manager mgr = new Manager();
            var obj = new byte[1024];

            var refContainer = new RefContainer();
            refContainer.Target = obj;

            obj = null;

            mgr["abc"] = refContainer.Target;

            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
            Console.WriteLine(mgr["abc"] != null); // true (still ref'd by "obj")

            refContainer = null;

            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
            Console.WriteLine(mgr["abc"] != null); // false (no remaining refs)
        }
    }

    class RefContainer
    {
        public object Target { get; set; }
    }

    class Manager
    {
        Dictionary<string, WeakReference> refs =
        new Dictionary<string, WeakReference>();
        public object this[string key]
        {
            get
            {
                WeakReference wr;
                if (refs.TryGetValue(key, out wr))
                {
                    if (wr.IsAlive)
                        return wr.Target;
                    refs.Remove(key);
                }
                return null;
            }
            set
            {
                refs[key] = new WeakReference(value);
            }
        }
    }
}

Running this program gives the following expected result:
True
False
Press any key to continue . . .

However change this:
var refContainer = new RefContainer();
refContainer.Target = obj;

To this (using Object Initializer syntax):
var refContainer = new RefContainer() { Target = obj };

Gives the following output:
True
True
Press any key to continue . . .

What's going on here? Why would lifetime of the reference be different just because of using Object Initializer?

A:

Why would lifetime of the reference be different just because of using Object Initializer?

I can't actually reproduce your problem anyway, but I suspect it's because this:
var refContainer = new RefContainer() { Target = obj };

is equivalent to:
var tmp = new RefContainer();
tmp.Target = obj;
var refContainer = tmp;

... so you end up with an extra reference to the object on the stack. Now when running not under the debugger, I'd expect the GC to notice that that stack location is never read again, and allow the object to be garbage collected - but as you're running under the debugger, the GC is more conservative, and I suspect it treats all stack variables as GC roots.
That's just a guess though - without being able to reproduce it anyway, it's hard to say for sure.
EDIT: Your assignments of obj = null; and refContainer = null; are pointless under non-debug mode; because the variables aren't read after that point anyway, the GC ignores them as GC roots.


Q:

Why is the set of positive definite matrices in $\mathbb R^{n\times n}$ a positive cone

The set of positive definite matrices in $\mathbb R^{n\times n}$ is geometrically a positive cone. This statement appears in almost every article on real positive definite matrices I read but without a proof. Where can I find a general proof, please? In addition, if I assume this statement is true, does it imply that the set of positive definite matrices is a manifold or a sub-manifold of $\mathbb R^n$ for some $n$?

A:

It's immediate from the definitions. An $n\times n$  real matrix $A$ is positive definite if (1) it is symmetric ($A^t=A$) and (2) $v^tAv>0$ for all non-zero column vectors $v\in\mathbb R^n$. The 1st condition is linear, so defines a linear subspace of $\mathbb R^{n^2},$ of dimension $n(n+1)/2$ (easy exercise). The 2nd condition defines an  open subset of $\mathbb R^{n(n+1)/2}$ which is a convex cone; ie a subset  closed under linear combinations with positive coefficients. This is very easy to verify. To show that its open you use the fact that $(v,A)\mapsto v^tAv$ is a continuous function. Thus your set is an $n(n+1)/2$ dimensional manifold, a convex open subset of $\mathbb R^{n(n+1)/2}$.


Q:

Gridview sorting not working with Item template

I have a problem, please I hope anyone can help me. I'm trying to sort one datagridview in my job.
The app has layers and for get data the data layer uses lists.
So, for sorting I try to convert that list in dataTable and using it in GridViewSortEventArgs.
One detail: I'm using paging
this is relevant part of my code:
Define class for the data:
public class Cajas
{
    public Cajas()
    { }

    private string clienteCodigo;
    public string ClienteCodigo
    {
        get { return clienteCodigo; }
        set { clienteCodigo = value; }
    }
    //-------------------------------

    private string cajaCodigo;
    public string CajaCodigo
    {
        get { return cajaCodigo; }
        set { cajaCodigo = value; }
    }
    //-------------------------------

    private int cajaNumero;
    public int CajaNumero
    {
        get { return cajaNumero; }
        set { cajaNumero = value; }
    }
    //-------------------------------

    private string cajaContenido;
    public string CajaContenido
    {
        get { return cajaContenido; }
        set { cajaContenido = value; }
    }
    //-------------------------------

    private DateTime fecEmisionDoc;
    public DateTime FecEmisionDoc
    {
        get { return fecEmisionDoc; }
        set { fecEmisionDoc = value; }
    }

    public Cajas(string cliCod, string cajCod, int cajNum, string cajCon, DateTime fecEmi)
    {
        this.ClienteCodigo = cliCod;
        this.CajaCodigo = cajCod;
        this.CajaNumero = cajNum;
        this.CajaContenido = cajCon;
        this.FecEmisionDoc = fecEmi;

    }

}

In the data layer this is for the query:
    public List<Cajas> Cajas_Buscar_CajaXCont(string clienteCodigo, string cajaContenido)
{
    List<Cajas> ListCajasxContenido = new List<Cajas>();
    string storedProcedure = "CAJAS_BUSCAR_CAJAXCONT";

    using (DbConnection con = dpf.CreateConnection())
    {
        con.ConnectionString = conStr;
        using (DbCommand cmd = dpf.CreateCommand())
        {
            cmd.Connection = con;
            cmd.CommandText = storedProcedure;
            cmd.CommandType = CommandType.StoredProcedure;

            DbParameter param1 = cmd.CreateParameter();
            param1.DbType = DbType.String;
            param1.ParameterName = "CLIENTE_CODIGO";
            param1.Value = clienteCodigo;
            cmd.Parameters.Add(param1);

            DbParameter param2 = cmd.CreateParameter();
            param2.DbType = DbType.String;
            param2.ParameterName = "CONTENIDO_CAJA";
            param2.Value = cajaContenido;
            cmd.Parameters.Add(param2);

            con.Open();
            using (DbDataReader dr = cmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    try
                    {
                        //creamos un objeto de tipo Caja, y por c/ registro encontrado en la db, insertamos
                        Cajas cajaBus = new Cajas();

                        cajaBus.ClienteCodigo = dr["CLIENTE"].ToString();
                        cajaBus.CajaCodigo = dr["CODIGO CAJA"].ToString();
                        cajaBus.CajaNumero = Convert.ToInt16(dr["NUM"].ToString());
                        cajaBus.CajaContenido = dr["CONTENIDO"].ToString();

                        if (Convert.IsDBNull(dr["F.EMI"].ToString())) //para manejar los valores DBnull
                        {
                            cajaBus.FecEmisionDoc = Convert.ToDateTime("9999-01-01"); //de lo contrario c# no los podra interpretar
                        }
                        else
                        {
                            cajaBus.FecEmisionDoc = Convert.ToDateTime(dr["F.EMI"]);
                        }

                        ListCajasxContenido.Add(cajaBus);
                    }
                    catch (System.InvalidCastException)
                    { }
                    catch (System.FormatException)
                    { }
                }
            }

        }
    }
    return ListCajasxContenido;

}

for get data on grid I call it
protected void sacbus_Consul_Cajas_x_Cont()
{
    gvwSacBus_Docs.DataSource = null;
    gvwSacBus_Docs.DataBind();
    gvwSacBus_Docs.DataSource = cajaBL.sacbus_Consul_Cajas_x_Cont(lbl_SacBus_CliCod.Text,
                                                        txt_SacBus_Criter.Text);
    gvwSacBus_Docs.DataBind();

    if (gvwSacBus_Docs.Rows.Count == 0)
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(), "AlertScript", "alert('No Encontrado!');", true);
    }

}

Now for sorting I get this:
public SortDirection dir

{
    get
    {
        if (ViewState["CajaContenido"] == null)
        {
            ViewState["CajaContenido"] = SortDirection.Ascending;
        }
        return (SortDirection)ViewState["CajaContenido"];
    }

    set
    {
        ViewState["CajaContenido"] = value;
    }
}

I convert the data to Datatable
public class ListtoDataTable
{
    public DataTable ToDataTable<T>(List<T> items)
    {
        DataTable dataTable = new DataTable(typeof(T).Name);
        //Get all the properties by using reflection
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo prop in Props)
        {
            dataTable.Columns.Add(prop.Name); //Setting column names as Property names
        }
        foreach (T item in items)
        {
            var values = new object[Props.Length];
            for (int i = 0; i < Props.Length; i++)
            {

                values[i] = Props[i].GetValue(item, null);
            }
            dataTable.Rows.Add(values);
        }

        return dataTable;
    }
}

So, when I try to make the sorting I use:
protected void gvwSacBus_Docs_Sorting(object sender, GridViewSortEventArgs e)
{
    gvwSacBus_Docs.DataSource = cajaBL.sacbus_Consul_Cajas_x_Cont(lbl_SacBus_CliCod.Text,
                                                        txt_SacBus_Criter.Text);
    gvwSacBus_Docs.DataBind();
ListtoDataTable lsttodt = new ListtoDataTable(); //convert list to datatable
    databito = lsttodt.ToDataTable(cajaBL.sacbus_Consul_Cajas_x_Cont(lbl_SacBus_CliCod.Text,
                                                        txt_SacBus_Criter.Text));

    string SortDir = string.Empty;

    if (dir == SortDirection.Ascending)

    {
        dir = SortDirection.Descending;
        SortDir = "Desc";
    }

    else
    {
        dir = SortDirection.Ascending;
        SortDir = "Asc";
    }

    DataView sortedView = new DataView(databito);
    sortedView.Sort = e.SortExpression + " " + SortDir;

    gvwSacBus_Docs.DataSource = sortedView;
    gvwSacBus_Docs.DataSource = cajaBL.sacbus_Consul_Cajas_x_Cont(lbl_SacBus_CliCod.Text,
                                                        txt_SacBus_Criter.Text);
    gvwSacBus_Docs.DataBind();
}

In the gridview I call what i've created:
AllowSorting="true" OnSorting="gvwSacBus_Docs_Sorting">

the app uses Item templates:
<asp:TemplateField HeaderText="CONTENIDO" SortExpression="CajaContenido">

Please, I hope anyone can help me
best regards!!

A:

Why are you converting a List to a DataTable? You can bind List to a GridView.
gvwSacBus_Docs.DataSource = myList;

Anyway if you want to sort a DataTable you do it like this. You have to use ToTable
dataTable.DefaultView.Sort = e.SortExpression + " " + SortDir;
gvwSacBus_Docs.DataSource = dataTable.DefaultView.ToTable();


Q:

Can a dogmatic person engage in intellectually honest inquiry?

Can someone fooling themselves still be intellectually dishonest?
Certain people may be dogmatic theists and believe that 'D' (for dogma) is true, and would really believe that D is true no matter what evidence they might find to the contrary. For such a person to engage in philosophical (or scientific, etc.) inquiry is somewhat perfunctory, because no matter what logical conclusion (s)he may come to, even if it contradicts D, would still believe that D is true. This is not necessarily a usual case of intellectual dishonesty or the like where someone looks for arguments to support his/her foregone conclusion, because in this case the person has honestly believes that D is true.
For example, someone I know is planning on writing a paper for his Master's degree in bioethics on the subject of circumcision, but he himself believes - for dogmatic/religious reasons - that circumcision is morally permissible (or even obligatory, I wouldn't put that past him) and he will write a paper supporting this dogmatic position. However, I don't think that this is for political or any other reason other than the fact that, no matter what he reads or reasons, he will continue to honestly believe in this opinion.
Is that still intellectually dishonest?

A:

Example
An example I am aware of is the Torah Codes, in which the birth and death dates of important Rabbis are supposedly encoded close to their names in the Bible. Some very intelligent researchers found extraordinarily strong evidence using recognised statistical techniques, and their results were published in a secular peer-reviewed journal. It had many people convinced for a time, until other researchers demonstrated methodological problems that were the probable source of the amazing evidence. It is likely that the researchers "tuned" their experiment, settling on a sample which confirmed their hypothesis, and then presenting their tuned sample as an independently compiled sample.
When you disregard confounding evidence, as is common with religious belief, any statistics that you use as justification for your beliefs is automatically useless. Based on this, I think it is extremely hard to take seriously research done by people with religiously predetermined opinions.
Meaning of "Intellectual Honesty"
The standard of intellectual honesty is more rigorous than just having knowledge.
For instance, true belief does not consititute knowledge. For knowledge it is necessary that a believer have justification to support their belief. But the believer must only be aware of the justification for their belief for it to be knowledge. The belief need not be caused by the justification.
In contrast, I don't think that simply having justification constitutes intellectual honesty. It is not just necessary that the believer is aware of the justification, I think they must believe an assertion because of the justification, or at least be open to disbelieving it should the evidence point in the opposite direction.
While an (hypothetical) entirely irrational person may have true beliefs and untrue beliefs, none of their beliefs constitute knowledge because the truth of their beliefs is accidental. They do not know (or understand) the difference between their true and untrue beliefs.
Likewise, a person with an overriding faith may have justified beliefs and unjustified beliefs. Although they know and understand justification, this time they simply do not care about it. Whether their beliefs have justification or not is accidental, and so the truth of their beliefs is still accidental.
Such a person may be very intelligent, and may in other ways be honest, but as the truth of their beliefs is still fundamentally accidental, it can be difficult to trust them. Even without lies, if they do not believe because of justifications, and would not be able to be swayed by justifications, they are still intellectually dishonest.


Q:

Один файл js не видит действия другого

Есть два файла *.js , в первом создание дива.
Во втором пытаюсь привязать к этому событие onclick, но выводит Uncaught TypeError: Cannot set property 'onclick' of null. Сделать все в одном файле не получится.
Первый файл успел исполниться , так-как в html этот див отобразился.
Код первого файла:
document.getElementsByTagName("body")[0].innerHTML = "

"
Код второго файла:
document.getElementById("class").onclick = function(event){}
Скрипты без async/defer

A:

Из-за window.onload первый файл, который должен создавать поле, выполнялся после загрузки всего документа. А так-как второй файл выполнялся сразу как только браузер его находил то он не мог прицепить событие onclick к полю, которое на этот момент еще не создано первым файлом.


Q:

Is there any need to use patch:after with Unicorn configuration files

I'm working in a Helix solution and have noticed things like:
<configuration name="Feature.MyModuleName"
               dependencies="Foundation.SomethingElse"
               patch:after="configuration[@name='Foundation.Core']">

To me, the dependencies attribute seems like all you should need.
Is it really necessary patch:after as well as the dependencies attribute?

A:

Yes. At least potentially.
patch:after happens when Sitecore.Configuration.Factory reads and parses and constructs the object graph that the configuration represents. So at Initialize time of the application. There could be Foundation level configuration entries (like default serializer and so on) that need to be set up, before your Feature level configuration is read and parsed.
The dependencies attribute affects Unicorn sync order at runtime. So much much later in process/lifecycle of your application.


Q:

Ignite Local Entries and Spilled to Disk Entries

For apache Ignite, when a key-value cache is spilled to disk is it spilled a key at a time or will it spill part of the value to disk?
In addition, for IgniteCache.localentries() will that automatically read all the values from disk or is there a way to traverse the in-memory ones first?

A:

Eviction happens on per-entry basis. E.g., you can't remove only half of the value from memory.
As for localEntries method, its behavior depends on provided CachePeekMode(s). For example, to get entries from all storage layers, call it like this:
cache.localEntries(CachePeekMode.ALL);


Q:

Does the paladin's Divine Health feature protect against both common and magical diseases?

By 3rd level, a Paladin gains the following ability (PHB, pg. 85):

Divine Health: The divine magic flowing through you makes you immune to disease.

Does this protect against both common AND magical disease?
There is no differentiation between the two. Disease is simply disease in the relevant entries (which I can't find anymore). A few spells afflict you with disease; sickly common folk may be diseased, and certain magical aura's on enemies may inflict a diseased state. Since these all count under the 'Disease' umbrella, and the Paladin trait simply says a magical energy is making you immune to disease... I assume this is read as "Immune to [all] disease."

A:

As you say: the game makes no such distinction between mundane and magical diseases with this ability, with all diseases just being diseases as far as it's concerned. Divine Health will protect you from both the measles and death dog saliva, equally.
This is congruent with how Paladins' miraculous healthiness works in many prior editions of the game too, so it's certainly not an oversight to not distinguish between mundane and magical disease.
Aside, the game otherwise does make a distinction between magical and mundane diseases (see the descriptions of spells like raise dead and resurrection) but Divine Health doesn't discriminate and defeats them all.


Q:

Why can't I mount my USB drive on ArchLinux?

I just started running ArchLinux and things were going swimmingly enough until I ran into this problem--I feel like I'm missing something obvious but I'm just not sure what it is.
When I try to mount my USB stick, I can't find the device in /dev.
Here's the dmesg from when I plug the stick in:
USB 1-8: new high speed USB device using ehci_hcd and address 6

According to the relevant ArchLinux page I gather that I'm supposed to see the device node there. I don't see it though.
Here's my lsusb output:
Bus 001 Device 006: ID 13fe:1f00 Kingston Technology Company Inc. DataTraveler 2.0 4GB Flash Drive / Patriot Xporter 32GB (PEF32GUSB) Flash Drive

When I take a look in /dev, I see sda, sda1..sda4, but I'm pretty sure that's just my hard drive and its partitions.
Does anybody have any guesses as to what I'm missing?

A:

Restart solved this for me. It was possibly related to the fact that I updated the kernel and restart was needed for some reason.


Q:

How to create a query that consider a match even if it has two different letters

I want some technique to solve my problem. I am using Postgresql 10.
I want to create a query that select substrings even if there's a difference of two letters. My language, portuguese, has many letters with same sound and people really make mistakes when typing.
Roughly what I want to do is this.
if I have a product name with the name "automóvel grande"
atomóvel grande" would match  //one letter is missing

 automovel grnde" would match //lack accent and letter is missing

  automovell grnde would match // lack of accent and the "l" was repeated

I used pg_trgm sometime ago and in my memory it worked, but, now, that I am using it again I am really getting some weird results.
I am using a setting like this:
ALTER DATABASE mydb SET pg_trgm.word_similarity_threshold = 0.2;

It is not able to match "capacete" when typing "capoceti".
I think the two words are similar enough. Chaning the threshold doesn't affect the result.

A:

I would suggest using Levenshtein Distance (https://en.wikipedia.org/wiki/Levenshtein_distance). It is the number of operations you need to change one string to another including insertion, deletion or changing a letter by another.
First, create the extension by running this:
CREATE EXTENSION fuzzystrmatch;

Then, you can use levenshtein (string1, string2) to find the distance (integer) between string1 and string2. After you run levenstein for your columns, filter the ones with a distance of 2 or less.
In your case, try this:
Select levenshtein('capacete', 'capoceti')

and you will get the distance of 2.
For more info on the string similarities on postgres see here: https://www.postgresql.org/docs/9.1/fuzzystrmatch.html


Q:

Want to import a library into my Java project

I would like to add this to my imports and use it to verify URI addresses however, I am having trouble figuring out how to properly import this http://www.jdom.org/docs/apidocs/org/jdom2/Verifier.html. Do I have to update my Maven repo? I understand that it is included in java.lang.Object, but when I include that it can't find Verifier.
Can someone please help me understand the problem here?
Ejay

A:

You can get JDOM 2.0.2 from Maven Central Repository:
<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom</artifactId>
    <version>2.0.2</version>
</dependency>

Here is a link to Maven Central Search for JDOM 2.0.2
I just pulled down jdom-2.0.2.jar from here and verified that it does contain org.jdom2.Verifier.class


Q:

draw an arbitrary line with OpenGL(i.e. no limit on axis range)

I want to draw a 2D line with parameters defined by user. But the range of x and y axis is [-1,1].
How can I draw the line that can be completely displayed in the window? I used gluOrtho2D(-10.0, 10.0, -10.0, 10.0) but it doesn't seem a good choice because the range is dynamic according to the parameters.
For example, the line is y=ax^3+bx^2+cx+d. the range of x is [1, 100].
My code is:
#include "pch.h"
#include<windows.h>

#include <gl/glut.h>

#include <iostream>
using namespace std;

double a, b, c, d;
void init(void)
{
    glClear(GL_COLOR_BUFFER_BIT);
    glMatrixMode(GL_PROJECTION);
    gluOrtho2D(-10.0, 10.0, -10.0, 10.0);
}

double power(double x, int p) {
    double y = 1.0;
    for (int i = 0; i < p; ++i) {
        y *= x;
    }
    return y;
}

void linesegment(void)
{
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(1, 0, 0);
    glPointSize(1);

    glBegin(GL_POINTS);
    for (int i = 1; i <= 10; ++i) {
        double y = a * power(i, 3) + b * power(i, 2) + c * i + d;
        glVertex2f(i, y);
    }
    glEnd();

    glFlush();
}

int main(int argc, char**argv)

{
    if (argc < 4) {
        cout << "should input 4 numbers" << endl;
        return 0;
    }

    a = atof(argv[1]);
    b = atof(argv[2]);
    c = atof(argv[3]);
    d = atof(argv[4]);

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowPosition(50, 100);
    glutInitWindowSize(400, 300);
    glutCreateWindow("AnExample");

    init();

    glutDisplayFunc(linesegment);
    glutMainLoop();

    return 0;
}

A:

Setting projection matrix is not a one-time-only operation. You can change it anytime you like. As a matter of fact, the way you do init is strongly discouraged. Just set the projection parameters in your drawing function. Also use standard library functions and don't roll your own. No need to implement power yourself. Just use the pow standard library function. Last but not least, use double buffering; for it gives better performance, and has better compatibility.
#include "pch.h"
#include <windows.h>

#include <gl/glut.h>

#include <iostream>
#include <cmath>
using namespace std;

double a, b, c, d;
double x_min, x_max, y_min, y_max; // <<<<---- fill these per your needs

void linesegment(void)
{
    glClear(GL_COLOR_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(x_min, x_max, y_min, y_max, -1, 1);

    glColor3f(1, 0, 0);
    glPointSize(1);

    glBegin(GL_POINTS);
    for (int i = 1; i <= 10; ++i) {
        double y = a * pow(i, 3) + b * pow(i, 2) + c * i + d;
        glVertex2f(i, y);
    }
    glEnd();

    glFlush();
}


Q:

replacing some fields in a line with the fields in the same columns in the next line

How can I parse the following tab delimited file to see if the 5th field is empty or not and if it is empty, replace c1 with c2 and d1 with d2. The actual file has a large number of rows with some having their 5th field empty.
a0  b0  c0  d0  e0
a1  b1  c1  d1  e1
a2  b2  c2  d2
a3  b3  c3  d3  e3

A:

Given:
$ cat so.txt
a0  b0  c0  d0  e0
a1  b1  c1  d1  e1
a2  b2  c2  d2
a3  b3  c3  d3  e3

You can write a filter in Python:
#!/usr/bin/python

import fileinput
from collections import deque
d=deque(maxlen=1)
for line in fileinput.input():
    sp=line.split()
    if len(sp)==4 and d:
        d[-1][2]=sp[2]
        d[-1][3]=sp[3]
    else:
        if d: print '\t'.join(d[-1])
        d.append(sp)
else:
    print '\t'.join(d[-1])

Since the deque is specified with max length of 1, it will only hold 1 line in memory at any given time. That means this filter will never have more than two lines in memory.
Then:
$ ./so.py so.txt
a0  b0  c0  d0  e0
a1  b1  c2  d2  e1
a3  b3  c3  d3  e3

And redirect that to the desired file.
Notes: will not work if there are multiples lines in a row that are only four fields or if the first line has four fields. You did not specify those results however...


Q:

jQuery carousel transformation

How can I transform jQuery carousel to show 3x3 square of images instead of 1x3?
From:
<- |image| |image| |image| ->

To:
   |image| |image| |image|
<- |image| |image| |image| ->
   |image| |image| |image|

My source code is like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

  <link rel="stylesheet" href="css/style.css" type="text/css" />

And this:
.infiniteCarousel{
position: relative;
float: right;
width: 501px;
margin: 193px 0 0 -2px;
z-index: 10000;
}
.infiniteCarousel .wrapper{
position: absolute;
top: 0;
min-height: 10em;
width: 395px;
margin: 0 40px;
overflow: auto;
}
.infiniteCarousel ul a img{border: none;}
.infiniteCarousel .wrapper ul{
position: absolute;
padding:0;
top: 0;
width: 9999px;
margin:0;
list-style-image:none; ist-style-position:outside; list-style-type:none;
}
.infiniteCarousel ul li{
display:block;
float:left;
padding: 10px 5px;
height: 124px;
width: 124px;
}
.infiniteCarousel ul li a img{display:block;}
.infiniteCarousel .arrow{
display: block;
height: 50px;
width: 50px;
background: url(../images/arrow.png) no-repeat 0 0;
text-indent: -999px;
position: absolute;
top: 33px;
cursor: pointer;
}
.infiniteCarousel .forward{background: url(../images/arrowright.png) no-repeat 0 0; right: 3px;}
.infiniteCarousel .back{background: url(../images/arrowleft.png) no-repeat 0 0; left: -12px;}
.infiniteCarousel .forward:hover{background: url(../images/arrowrighthover.png) no-repeat 0 0;}
.infiniteCarousel .back:hover{background: url(../images/arrowlefthover.png) no-repeat 0 0;}

A:

How about clearing after each third li:

Notice the addition of
 above. The CSS for clear class is:
.clear{
  clear:both;
}


Q:

(2/2) ErrorException Object of class stdClass could not be converted to int in laravel 5

I want to create a tax summary of invoice in which i want to add total according to different tax rate.For example:- 2.5% taxrate has its own products and 6% taxrate has its own product.i want to do this in for loop.I have used following code but it did not work.please tell me what is wrong in this code.it did not show correct total.I have a table name is sales_items. Its field are id,invoice_id,cgst_percentage,cgst_amount,sgst_percentage etc.The image is as

Controller.php
    $data['query1']= DB::table('sales_items')->distinct()->get(['cgst_percentage']);
    // I am using this variable in foreach loop in view file.

View.blade.php
    <?php $data_total= array();  ?>
    <?php $cgst_unique_data= array(); ?>

 @foreach($query1 as $cgst_data=>$value)

    <?php

    $cgst_unique_data= DB::table('sales_items')->where('cgst_percentage','=',$value->cgst_percentage)->where('invoice_id','=',$sales_item->invoice_id)->get();

    ?>

     @foreach($cgst_unique_data as $total=>$value)

     <?php

     $data_total = $total_amount + $total;
     $data_total= $data_total + $value;
     ?>
     @endforeach

     {{ $data_total }}

 @endforeach

A:

$value variable is an object that holds a row from your cgst_unique_data query results. You can't simply add that to other integer variables like you do in
$data_total= $data_total + $value;

You'll need to access a specific column from that row that you want to add. If the column name was someName, you'd need to do:
$data_total= $data_total + $value->someName;


Q:

Is it possible to romance Jack in Mass Effect 2 without re-playing Mass Effect 1?

I'm trying to romance Jack in Mass Effect 2, but I don't want to replay the first Mass Effect and when I chose the "new game" option it chooses for the default romance option of Kaidan.
How do I romance Jack without replaying Mass Effect?

A:

Who you romanced in Mass Effect 1 has no impact on romancing Jack, who you don't meet until Mass Effect 2 anyway. All that matters is that you don't romance somebody else while you're romancing Jack, as she has very low self esteem and doesn't handle it very well at all.
When completing her loyalty mission ensure you review all of the available logs and talk to Jack afterwards to get her feelings on what you've learned. It's best to choose the caring dialogue option whenever one presents itself to you while taking with Jack.
Later in the game after completing both Jack and Miranda's loyalty mission you will come back aboard the Normandy to find them fighting with each other. You must either side with Jack or use your Paragon/Renegade dialogue option to break up the fight if you want to keep Jack happy.


Q:

Everything in one slide for a theme

I have the following problem. I use a theme, where it seems, that I can't put everything in one slide. First, there is an empty page, than the picture, than then every item one after another. I want to have a picture on the left side and the text on the right side to appear at once in one slide. Is there a way to do it with the following code?
I use the FUBerlin theme, which you can find here:
http://ctanhg.scharrer-online.de/pkg/beamer-fuberlin.html
\documentclass[t,smaller,compress]{FUbeamer}

\usepackage[ngerman]{babel}
\usepackage[utf8x]{inputenc}
\begin{document}
\title{title}
\author{Anonymous \\
 Betreuer: Dr. Anonymous}
\date{1. Juli 2014}
\titlegraphic{geo}
\fachbereich{Institut}
\maketitle

\begin{frame}{Inhaltsverzeichnis}
\tableofcontents
\end{frame}

\section{Motivation}

\begin{frame}
\begin{columns}[T]
     \begin{column}[T]{5cm}
        pic
        \includegraphics[height=6cm]{region_krueg.jpg}
        \end{column}
        \begin{column}[T]{5cm}
\begin{itemize}
\item text
\item text
\item text
\item text
\item text
\end{itemize}

   \end{column}
  \end{columns}
\end{frame}

\begin{frame}
\begin{columns}[T]
     \begin{column}[T]{5cm}
        %Bild
        \includegraphics[height=5cm]{verteilung_kor.jpg}
        \end{column}
        \begin{column}[T]{5cm}
\begin{itemize}
\item text
\item text
\item text
\item text
\item text
\end{itemize}

   \end{column}
  \end{columns}
\end{frame}

\end{document}

If it isn't possible with this theme, could somebody give me an alternative theme, where it works? Help is much appreciated. It's my first presentation in beamer.
Greetz

A:

I've looked at the FUbeamer.cls and to stop the one-by-one display of the listed items, it's very simple...
You just have to comment the line 69 of the FUbeamer.cls file.
It's this line : \beamerdefaultoverlayspecification{<+-| alert@+>}
It specify the default imetize parameters...
By commenting it, you just refer back to the classical method, everything on 1 slide.
I hope it helped


Q:

Keys in JSON / VBA

hope someone as a little hint for me solving my problem.
I have a Json response like this:
"modules": [
    {
        "localId": "598d58882e00008b1174fa0a",
        "legs": [
            {
                "markerIndex": 0,
                "localId": "5a2ec9db250000cc0189fbac",
                "connections": [
                    {
                        "jsonClass": "TransitCO",
                        "localId": "5a882b0b26000039187fd0bb",
    {
        "localId": "598d58c82c00005411c4a7e1",
        "returnConnections": [
            {
                "jsonClass": "ActivityElementCO",
                "localId": "5a8aeacc250000641c1d389a",
    {
        "localId": "598d58d62e0000a71174fa0c",
        "legs": [
            {
                "markerIndex": 1,
                "localId": "5a85c668200000ea1b040503",
                "connections": [
                    {
                        "jsonClass": "TransitCO",
                        "localId": "5a882b0b26000039187fd0be",

I can locate 1 localId by calling:
Dim fd As Integer
Set var_dmc = JsonConverter.ParseJson(MyDMC.ResponseText)
Set dmc = Worksheets("dmc")
fd = 25
For Each item In var_dmc("modules")(1)("legs")
dmc.Cells(fd, 2) = item("connections")("localId")
fd = fd + 1
Next

Now my VBA code should read out each "localId" under "connections" IF "jsonClass" is = TransitCO.
Tried with each for and coombinations of "if then"s but nothing works.
Any ideas?
Kind regards,
Chris

A:

Here is a lengthy answer. There is are a lot of empty structure within the JSON (maybe due to edit. But I have coded to show how you would still access though have commented out many of these sections. The commented out typename statements are to show you what structures are being returned at each stage.
Admittedly, this is currently everything so I will look to a shorter version.
Note: I am reading the JSON in from a file on my desktop.
For a better understanding of this see my answer to this question.
Option Explicit

Sub GetValues()
    'Tools references > ms scripting runtime
    Dim FSO As FileSystemObject
    Set FSO = New FileSystemObject

    Dim JsonTS As TextStream
    Dim JsonText As String

    Set JsonTS = FSO.OpenTextFile(ThisWorkbook.Path & Application.PathSeparator & "SOQuestion.txt", ForReading)

    JsonText = JsonTS.ReadAll
    JsonTS.Close

    Dim Json As Object

    Set Json = ParseJson(JsonText)

    Dim col As Collection
    Set col = Json("modules")

    'Debug.Print col.Count '3 items
    Dim item As Variant
    Dim key1 As Variant
    Dim item1 As Variant
    Dim key2 As Variant

    For Each item In col

        For Each key1 In item.Keys

            If key1 = "localId" Then

                Debug.Print key1 & " : " & item(key1)

            ElseIf key1 = "legs" Then            'collection

                For Each item1 In item(key1)

                    'Debug.Print TypeName(item1) '2 dict

                    For Each key2 In item1.Keys
                        '  Debug.Print TypeName(item1(key2)) ' 2 collection; 2 dict; 4 double; 6 string

                        Dim dataStructure As String

                        dataStructure = TypeName(item1(key2))

                        Select Case dataStructure

                        Case "Double", "String"

                            Debug.Print key1 & " : " & key2 & item1(key2)

                        Case "Dictionary"

                            Dim key3 As Variant

                            For Each key3 In item1(key2).Keys

                                'Debug.Print item1(key2)(key3) 'This is empty

                            Next key3

                        Case "Collection"        ' 2 collections with 1 item which are both dictionaries

                            Dim key4 As Variant

                            For Each key4 In item1(key2)(1).Keys

                                'Debug.Print TypeName(item1(key2)(1)(key4)) ' 1 boolean; 2 collection ; 2 dict; 8 strings

                                Dim dataStructure2 As String
                                dataStructure2 = TypeName(item1(key2)(1)(key4))

                                Select Case dataStructure2

                                Case "Boolean", "String"

                                    Debug.Print key1 & " : " & key2 & " : " & key4 & " : " & item1(key2)(1)(key4)

                                Case "Collection" 'These are empty. As seen with  Debug.Print item1(key2)(1)(key4).Count

                                    '                                   Dim item2 As Variant
                                    '
                                    '                                   For Each item2 In item1(key2)(1)(key4)
                                    '
                                    '                                      ' Debug.Print TypeName(item1(key2)(1)(key4)(item2)) 'empty
                                    '                                       'Debug.Print key1 & " : " & key2 & " : " & key4 & " : " & item1(key2)(1)(key4)(item2)
                                    '
                                    '                                   Next item2

                                Case "Dictionary" 'these are empty

                                    'Dim key5 As Variant

                                    'Debug.Print item1(key2)(1)(key4).Count = 0; so; both; Empty

                                    '                                   For Each key5 In item1(key2)(1)(key4).Keys
                                    '
                                    '                                       Debug.Print TypeName(item1(key2)(1)(key4)(key5))
                                    '
                                    '                                   Next key5

                                End Select

                            Next key4

                        End Select

                    Next key2

                Next item1

            End If

        Next key1

    Next item

End Sub

And lazier, less robust, targeted version:
Option Explicit

Sub GetvaluesDict()
    'Tools references > ms scripting runtime

    Dim FSO As FileSystemObject
    Set FSO = New FileSystemObject

    Dim JsonTS As TextStream
    Dim JsonText As String

    Set JsonTS = FSO.OpenTextFile(ThisWorkbook.Path & Application.PathSeparator & "SOQuestion.txt", ForReading)

    JsonText = JsonTS.ReadAll
    JsonTS.Close

    Dim Json As Object

    Set Json = ParseJson(JsonText)

    Dim col As Collection
    Set col = Json("modules")

    Dim counter As Long
    Dim dict As Dictionary

    Set dict = New Dictionary

    Dim item As Variant

    For Each item In col                         'looking at items

        Dim key1 As Variant

        For Each key1 In item.Keys

            If key1 = "returnConnections" Or key1 = "legs" Then '6 collections

                Dim item1 As Variant

                For Each item1 In item(key1)     ' 6 dictionaries

                    Dim key2 As Variant

                    For Each key2 In item1.Keys

                        Dim dataStructure As String

                        dataStructure = TypeName(item1(key2))

                        Select Case dataStructure

                        Case "Double", "String", "Boolean"
                            counter = counter + 1
                            dict.Add counter, key1 & " : " & key2 & " : " & item1(key2)

                        Case "Collection"

                            Dim item2 As Variant

                            For Each item2 In item1(key2)

                                Dim key3 As Variant

                                For Each key3 In item2.Keys

                                    Select Case TypeName(item2(key3))

                                    Case "String"

                                        counter = counter + 1
                                        dict.Add counter, key1 & " : " & key2 & " : " & key3 & " : " & item2(key3)

                                    End Select

                                Next key3

                            Next item2

                        End Select

                    Next key2

                Next item1

            End If

        Next key1

    Next item

    Dim returns As Variant

    counter = 1

    For Each returns In dict.Keys

        If InStr(1, dict(returns), "TransitCO", vbBinaryCompare) > 0 Then

            Debug.Print dict(returns) & vbTab & dict(counter + 1)

        End If
        counter = counter + 1
    Next returns

End Sub


Q:

SDL, SFML, OpenGL, or just move to Java

I recently started a new project, and I'm wondering if I should change the technology now before it's too late.
I'm using SDL with C++, I have around 6 classes, and the game is going alright, but I got to this point where I have to rotate my sprite to make it point to the coordinates of the mouse.
It's a 2D topdown game, so if I pre-cached the images, I'd have to load 360 images, which is bad for memory. If I used SDL_glx, I could do the rotation real time, but I heard it'd drop my frame rate very drastically, and I don't want my game to be slow.
I also read I could use OpenGL, which is faster at these things. The problem is, how much would I have to change my code if I moved to OpenGL with SDL.
So, I considered moving to a completely different language - Java - which is much simpler, and would allow me to focus on the game and handle networking much more easily than with C++.
I am very confused, and would like to hear your opinion - thank you!

A:

If you're fairly new to game programming and programming in general, I recommend against starting out learning everything in C++. Either set your sights lower than sprite-based games while you learn C++ (e.g., practice with a text adventure while you get comfortable with the language) or go for the less cerebral, more fun route with another language.
Java is a good language to start game programming in if you're at least somewhat comfortable with object oriented programming. You have libraries like JogAmp, LWJGL, and Java Monkey Engine to get started, as well as tools like Eclipse.
Lua and Python have similar libraries to Java available and are also pretty good for getting something on screen relatively quickly and making it move around, although I have to defer to someone else's experience for starter libraries and tools for these languages.
If you're comfortable with C++ and would like to stick with it, then I think it comes down to a matter of personal experience, priorities, and taste. The options you listed are all good ones generally, but you'll want to read up on the APIs, strengths and weaknesses, and so on to see which one fits you best.
My hunch, though, is that you'd be happier working in another language for a while to get some experience before you come back to C++. There is plenty of general game programming experience to be gained elsewhere.
I hope this helps. Good luck.